forward port automation handling changes from 2.x, upto and including about rev 6981...
[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 "pbd/xml++.h"
26 #include "pbd/enumwriter.h"
27 #include "pbd/memento_command.h"
28 #include "pbd/stacktrace.h"
29 #include "pbd/convert.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/debug.h"
41 #include "ardour/delivery.h"
42 #include "ardour/dB.h"
43 #include "ardour/internal_send.h"
44 #include "ardour/internal_return.h"
45 #include "ardour/ladspa_plugin.h"
46 #include "ardour/meter.h"
47 #include "ardour/mix.h"
48 #include "ardour/monitor_processor.h"
49 #include "ardour/panner.h"
50 #include "ardour/plugin_insert.h"
51 #include "ardour/port.h"
52 #include "ardour/port_insert.h"
53 #include "ardour/processor.h"
54 #include "ardour/profile.h"
55 #include "ardour/route.h"
56 #include "ardour/route_group.h"
57 #include "ardour/send.h"
58 #include "ardour/session.h"
59 #include "ardour/timestamps.h"
60 #include "ardour/utils.h"
61 #include "ardour/graph.h"
62
63 #include "i18n.h"
64
65 using namespace std;
66 using namespace ARDOUR;
67 using namespace PBD;
68
69 uint32_t Route::order_key_cnt = 0;
70 PBD::Signal1<void,string const&> Route::SyncOrderKeys;
71 PBD::Signal0<void> Route::RemoteControlIDChange;
72
73 Route::Route (Session& sess, string name, Flag flg, DataType default_type)
74         : SessionObject (sess, name)
75         , Automatable (sess)
76         , GraphNode( sess.route_graph )
77         , _active (true)
78         , _initial_delay (0)
79         , _roll_delay (0)
80         , _flags (flg)
81         , _pending_declick (true)
82         , _meter_point (MeterPostFader)
83         , _self_solo (false)
84         , _soloed_by_others_upstream (0)
85         , _soloed_by_others_downstream (0)
86         , _solo_isolated (0)
87         , _denormal_protection (false)
88         , _recordable (true)
89         , _silent (false)
90         , _declickable (false)
91         , _solo_control (new SoloControllable (X_("solo"), *this))
92         , _mute_control (new MuteControllable (X_("mute"), *this))
93         , _mute_master (new MuteMaster (sess, name))
94         , _have_internal_generator (false)
95         , _solo_safe (false)
96         , _default_type (default_type)
97         , _remote_control_id (0)
98         , _in_configure_processors (false)
99 {
100         processor_max_streams.reset();
101         order_keys[N_("signal")] = order_key_cnt++;
102 }
103
104 int
105 Route::init ()
106 {
107         /* add standard controls */
108
109         _solo_control->set_flags (Controllable::Flag (_solo_control->flags() | Controllable::Toggle));
110         _mute_control->set_flags (Controllable::Flag (_solo_control->flags() | Controllable::Toggle));
111
112         add_control (_solo_control);
113         add_control (_mute_control);
114
115         /* input and output objects */
116
117         _input.reset (new IO (_session, _name, IO::Input, _default_type));
118         _output.reset (new IO (_session, _name, IO::Output, _default_type));
119
120         _input->changed.connect_same_thread (*this, boost::bind (&Route::input_change_handler, this, _1, _2));
121         _output->changed.connect_same_thread (*this, boost::bind (&Route::output_change_handler, this, _1, _2));
122
123         /* add amp processor  */
124
125         _amp.reset (new Amp (_session));
126         add_processor (_amp, PostFader);
127
128         /* add standard processors: meter, main outs, monitor out */
129
130         _meter.reset (new PeakMeter (_session));
131         _meter->set_display_to_user (false);
132
133         add_processor (_meter, PostFader);
134
135         _main_outs.reset (new Delivery (_session, _output, _mute_master, _name, Delivery::Main));
136
137         add_processor (_main_outs, PostFader);
138
139         if (is_monitor()) {
140                 /* where we listen to tracks */
141                 _intreturn.reset (new InternalReturn (_session));
142                 add_processor (_intreturn, PreFader);
143
144                 ProcessorList::iterator i;
145
146                 for (i = _processors.begin(); i != _processors.end(); ++i) {
147                         if (*i == _intreturn) {
148                                 ++i;
149                                 break;
150                         }
151                 }
152
153                 /* the thing that provides proper control over a control/monitor/listen bus 
154                    (such as per-channel cut, dim, solo, invert, etc).
155                    It always goes right after the internal return;
156                  */
157                 _monitor_control.reset (new MonitorProcessor (_session));
158                 add_processor (_monitor_control, i);
159
160                 /* no panning on the monitor main outs */
161
162                 _main_outs->panner()->set_bypassed (true);
163         }
164
165         if (is_master() || is_monitor() || is_hidden()) {
166                 _mute_master->set_solo_ignore (true);
167         }
168
169         /* now that we have _meter, its safe to connect to this */
170
171         Metering::Meter.connect_same_thread (*this, (boost::bind (&Route::meter, this)));
172
173         return 0;
174 }
175
176 Route::~Route ()
177 {
178         DEBUG_TRACE (DEBUG::Destruction, string_compose ("route %1 destructor\n", _name));
179
180         /* do this early so that we don't get incoming signals as we are going through destruction 
181          */
182
183         drop_connections ();
184
185         /* don't use clear_processors here, as it depends on the session which may
186            be half-destroyed by now 
187         */
188
189         Glib::RWLock::WriterLock lm (_processor_lock);
190         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
191                 (*i)->drop_references ();
192         }
193
194         _processors.clear ();
195 }
196
197 void
198 Route::set_remote_control_id (uint32_t id, bool notify_class_listeners)
199 {
200         if (id != _remote_control_id) {
201                 _remote_control_id = id;
202                 RemoteControlIDChanged ();
203                 if (notify_class_listeners) {
204                         RemoteControlIDChange ();
205                 }
206         }
207 }
208
209 uint32_t
210 Route::remote_control_id() const
211 {
212         return _remote_control_id;
213 }
214
215 int32_t
216 Route::order_key (std::string const & name) const
217 {
218         OrderKeys::const_iterator i = order_keys.find (name);
219         if (i == order_keys.end()) {
220                 return -1;
221         }
222
223         return i->second;
224 }
225
226 void
227 Route::set_order_key (std::string const & name, int32_t n)
228 {
229         bool changed = false;
230
231         /* This method looks more complicated than it should, but
232            it's important that we don't emit order_key_changed unless
233            it actually has, as expensive things happen on receipt of that
234            signal.
235         */
236
237         if (order_keys.find(name) == order_keys.end() || order_keys[name] != n) {
238                 order_keys[name] = n;
239                 changed = true;
240         }
241
242         if (Config->get_sync_all_route_ordering()) {
243                 for (OrderKeys::iterator x = order_keys.begin(); x != order_keys.end(); ++x) {
244                         if (x->second != n) {
245                                 x->second = n;
246                                 changed = true;
247                         }
248                 }
249         }
250
251         if (changed) {
252                 order_key_changed (); /* EMIT SIGNAL */
253                 _session.set_dirty ();
254         }
255 }
256
257 /** Set all order keys to be the same as that for `base', if such a key
258  *  exists in this route.
259  *  @param base Base key.
260  */
261 void
262 Route::sync_order_keys (std::string const & base)
263 {
264         if (order_keys.empty()) {
265                 return;
266         }
267
268         OrderKeys::iterator i;
269         int32_t key;
270
271         if ((i = order_keys.find (base)) == order_keys.end()) {
272                 /* key doesn't exist, use the first existing key (during session initialization) */
273                 i = order_keys.begin();
274                 key = i->second;
275                 ++i;
276         } else {
277                 /* key exists - use it and reset all others (actually, itself included) */
278                 key = i->second;
279                 i = order_keys.begin();
280         }
281
282         bool changed = false;
283         
284         for (; i != order_keys.end(); ++i) {
285                 if (i->second != key) {
286                         i->second = key;
287                         changed = true;
288                 }
289         }
290
291         if (changed) {
292                 order_key_changed (); /* EMIT SIGNAL */
293         }
294 }
295
296 string
297 Route::ensure_track_or_route_name(string name, Session &session)
298 {
299         string newname = name;
300
301         while (!session.io_name_is_legal (newname)) {
302                 newname = bump_name_once (newname, '.');
303         }
304
305         return newname;
306 }
307
308
309 void
310 Route::inc_gain (gain_t fraction, void *src)
311 {
312         _amp->inc_gain (fraction, src);
313 }
314
315 void
316 Route::set_gain (gain_t val, void *src)
317 {
318         if (src != 0 && _route_group && src != _route_group && _route_group->is_active() && _route_group->is_gain()) {
319
320                 if (_route_group->is_relative()) {
321
322                         gain_t usable_gain = _amp->gain();
323                         if (usable_gain < 0.000001f) {
324                                 usable_gain = 0.000001f;
325                         }
326
327                         gain_t delta = val;
328                         if (delta < 0.000001f) {
329                                 delta = 0.000001f;
330                         }
331
332                         delta -= usable_gain;
333
334                         if (delta == 0.0f)
335                                 return;
336
337                         gain_t factor = delta / usable_gain;
338
339                         if (factor > 0.0f) {
340                                 factor = _route_group->get_max_factor(factor);
341                                 if (factor == 0.0f) {
342                                         _amp->gain_control()->Changed(); /* EMIT SIGNAL */
343                                         return;
344                                 }
345                         } else {
346                                 factor = _route_group->get_min_factor(factor);
347                                 if (factor == 0.0f) {
348                                         _amp->gain_control()->Changed(); /* EMIT SIGNAL */
349                                         return;
350                                 }
351                         }
352
353                         _route_group->apply (&Route::inc_gain, factor, _route_group);
354
355                 } else {
356
357                         _route_group->apply (&Route::set_gain, val, _route_group);
358                 }
359
360                 return;
361         }
362
363         if (val == _amp->gain()) {
364                 return;
365         }
366
367         _amp->set_gain (val, src);
368 }
369
370 /** Process this route for one (sub) cycle (process thread)
371  *
372  * @param bufs Scratch buffers to use for the signal path
373  * @param start_frame Initial transport frame
374  * @param end_frame Final transport frame
375  * @param nframes Number of frames to output (to ports)
376  *
377  * Note that (end_frame - start_frame) may not be equal to nframes when the
378  * transport speed isn't 1.0 (eg varispeed).
379  */
380 void
381 Route::process_output_buffers (BufferSet& bufs,
382                                sframes_t start_frame, sframes_t end_frame, nframes_t nframes,
383                                bool /*with_processors*/, int declick)
384 {
385         bool monitor;
386
387         bufs.is_silent (false);
388
389         switch (Config->get_monitoring_model()) {
390         case HardwareMonitoring:
391         case ExternalMonitoring:
392                 monitor = !record_enabled() || (_session.config.get_auto_input() && !_session.actively_recording());
393                 break;
394         default:
395                 monitor = true;
396         }
397
398         if (!declick) {
399                 declick = _pending_declick;
400         }
401
402         /* figure out if we're going to use gain automation */
403         _amp->setup_gain_automation (start_frame, end_frame, nframes);
404
405
406         /* tell main outs what to do about monitoring */
407         _main_outs->no_outs_cuz_we_no_monitor (!monitor);
408
409
410         /* -------------------------------------------------------------------------------------------
411            GLOBAL DECLICK (for transport changes etc.)
412            ----------------------------------------------------------------------------------------- */
413
414         if (declick > 0) {
415                 Amp::declick (bufs, nframes, 1);
416         } else if (declick < 0) {
417                 Amp::declick (bufs, nframes, -1);
418         }
419
420         _pending_declick = 0;
421
422         /* -------------------------------------------------------------------------------------------
423            DENORMAL CONTROL/PHASE INVERT
424            ----------------------------------------------------------------------------------------- */
425
426         if (_phase_invert.any ()) {
427
428                 int chn = 0;
429
430                 if (_denormal_protection || Config->get_denormal_protection()) {
431
432                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i, ++chn) {
433                                 Sample* const sp = i->data();
434
435                                 if (_phase_invert[chn]) {
436                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
437                                                 sp[nx]  = -sp[nx];
438                                                 sp[nx] += 1.0e-27f;
439                                         }
440                                 } else {
441                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
442                                                 sp[nx] += 1.0e-27f;
443                                         }
444                                 }
445                         }
446
447                 } else {
448
449                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i, ++chn) {
450                                 Sample* const sp = i->data();
451
452                                 if (_phase_invert[chn]) {
453                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
454                                                 sp[nx] = -sp[nx];
455                                         }
456                                 }
457                         }
458                 }
459
460         } else {
461
462                 if (_denormal_protection || Config->get_denormal_protection()) {
463
464                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
465                                 Sample* const sp = i->data();
466                                 for (nframes_t nx = 0; nx < nframes; ++nx) {
467                                         sp[nx] += 1.0e-27f;
468                                 }
469                         }
470
471                 }
472         }
473
474         /* -------------------------------------------------------------------------------------------
475            and go ....
476            ----------------------------------------------------------------------------------------- */
477
478         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
479
480                 if (bufs.count() != (*i)->input_streams()) {
481                         cerr << _name << " bufs = " << bufs.count()
482                              << " input for " << (*i)->name() << " = " << (*i)->input_streams()
483                              << endl;
484                 }
485                 assert (bufs.count() == (*i)->input_streams());
486                 
487                 (*i)->run (bufs, start_frame, end_frame, nframes, *i != _processors.back());
488                 bufs.set_count ((*i)->output_streams());
489         }
490 }
491
492 ChanCount
493 Route::n_process_buffers ()
494 {
495         return max (_input->n_ports(), processor_max_streams);
496 }
497
498 void
499 Route::passthru (sframes_t start_frame, sframes_t end_frame, nframes_t nframes, int declick)
500 {
501         BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
502
503         _silent = false;
504
505         assert (bufs.available() >= input_streams());
506
507         if (_input->n_ports() == ChanCount::ZERO) {
508                 silence_unlocked (nframes);
509         }
510
511         bufs.set_count (input_streams());
512
513         if (is_monitor() && _session.listening() && !_session.is_auditioning()) {
514
515                 /* control/monitor bus ignores input ports when something is
516                    feeding the listen "stream". data will "arrive" into the
517                    route from the intreturn processor element.
518                 */
519                 bufs.silence (nframes, 0);
520
521         } else {
522
523                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
524
525                         BufferSet::iterator o = bufs.begin(*t);
526                         PortSet& ports (_input->ports());
527
528                         for (PortSet::iterator i = ports.begin(*t); i != ports.end(*t); ++i, ++o) {
529                                 o->read_from (i->get_buffer(nframes), nframes);
530                         }
531                 }
532         }
533
534         write_out_of_band_data (bufs, start_frame, end_frame, nframes);
535         process_output_buffers (bufs, start_frame, end_frame, nframes, true, declick);
536 }
537
538 void
539 Route::passthru_silence (sframes_t start_frame, sframes_t end_frame, nframes_t nframes, int declick)
540 {
541         BufferSet& bufs (_session.get_silent_buffers (n_process_buffers()));
542         bufs.set_count (_input->n_ports());
543         write_out_of_band_data (bufs, start_frame, end_frame, nframes);
544         process_output_buffers (bufs, start_frame, end_frame, nframes, true, declick);
545 }
546
547 void
548 Route::set_listen (bool yn, void* src)
549 {
550         if (_solo_safe) {
551                 return;
552         }
553
554         if (_monitor_send) {
555                 if (yn != _monitor_send->active()) {
556                         if (yn) {
557                                 _monitor_send->activate ();
558                                 _mute_master->set_soloed (true);
559                         } else {
560                                 _monitor_send->deactivate ();
561                                 _mute_master->set_soloed (false);
562                         }
563
564                         listen_changed (src); /* EMIT SIGNAL */
565                 }
566         }
567 }
568
569 bool
570 Route::listening () const
571 {
572         if (_monitor_send) {
573                 return _monitor_send->active ();
574         } else {
575                 return false;
576         }
577 }
578
579 void
580 Route::set_solo_safe (bool yn, void *src)
581 {
582         if (_solo_safe != yn) {
583                 _solo_safe = yn;
584                 solo_safe_changed (src);
585         } 
586 }
587
588 bool
589 Route::solo_safe() const
590 {
591         return _solo_safe;
592 }
593
594 void
595 Route::set_solo (bool yn, void *src)
596 {
597         if (_solo_safe) {
598                 return;
599         }
600
601         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_solo()) {
602                 _route_group->apply (&Route::set_solo, yn, _route_group);
603                 return;
604         }
605
606         if (self_soloed() != yn) {
607                 set_self_solo (yn);
608                 set_mute_master_solo ();
609                 solo_changed (true, src); /* EMIT SIGNAL */
610                 _solo_control->Changed (); /* EMIT SIGNAL */
611         }
612 }
613
614 void
615 Route::set_self_solo (bool yn)
616 {
617         _self_solo = yn;
618 }
619
620 void
621 Route::mod_solo_by_others_upstream (int32_t delta)
622 {
623         if (_solo_safe) {
624                 return;
625         }
626
627         uint32_t old_sbu = _soloed_by_others_upstream;
628
629         if (delta < 0) {
630                 if (_soloed_by_others_upstream >= (uint32_t) abs (delta)) {
631                         _soloed_by_others_upstream += delta;
632                 } else {
633                         _soloed_by_others_upstream = 0;
634                 }
635         } else {
636                 _soloed_by_others_upstream += delta;
637         }
638
639         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 SbU delta %2 = %3 old = %4 sbd %5 ss %6 exclusive %7\n",
640                                                   name(), delta, _soloed_by_others_upstream, old_sbu, 
641                                                   _soloed_by_others_downstream, _self_solo, Config->get_exclusive_solo()));
642
643         /* push the inverse solo change to everything that feeds us. 
644            
645            This is important for solo-within-group. When we solo 1 track out of N that
646            feed a bus, that track will cause mod_solo_by_upstream (+1) to be called
647            on the bus. The bus then needs to call mod_solo_by_downstream (-1) on all
648            tracks that feed it. This will silence them if they were audible because
649            of a bus solo, but the newly soloed track will still be audible (because 
650            it is self-soloed).
651            
652            but .. do this only when we are being told to solo-by-upstream (i.e delta = +1),
653            not in reverse.
654          */
655
656         if ((_self_solo || _soloed_by_others_downstream) &&
657             ((old_sbu == 0 && _soloed_by_others_upstream > 0) || 
658              (old_sbu > 0 && _soloed_by_others_upstream == 0))) {
659                 
660                 if (delta > 0 || !Config->get_exclusive_solo()) {
661                         DEBUG_TRACE (DEBUG::Solo, "\t ... INVERT push\n");
662                         for (FedBy::iterator i = _fed_by.begin(); i != _fed_by.end(); ++i) {
663                                 boost::shared_ptr<Route> sr = i->r.lock();
664                                 if (sr) {
665                                         sr->mod_solo_by_others_downstream (-delta);
666                                 }
667                         }
668                 } 
669         }
670
671         set_mute_master_solo ();
672         solo_changed (false, this);
673 }
674
675 void
676 Route::mod_solo_by_others_downstream (int32_t delta)
677 {
678         if (_solo_safe) {
679                 return;
680         }
681
682         if (delta < 0) {
683                 if (_soloed_by_others_downstream >= (uint32_t) abs (delta)) {
684                         _soloed_by_others_downstream += delta;
685                 } else {
686                         _soloed_by_others_downstream = 0;
687                 }
688         } else {
689                 _soloed_by_others_downstream += delta;
690         }
691
692         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 SbD delta %2 = %3\n", name(), delta, _soloed_by_others_downstream));
693
694         set_mute_master_solo ();
695         solo_changed (false, this);
696 }
697
698 void
699 Route::set_mute_master_solo ()
700 {
701         _mute_master->set_soloed (self_soloed() || soloed_by_others_downstream() || soloed_by_others_upstream());
702 }
703
704 void
705 Route::set_solo_isolated (bool yn, void *src)
706 {
707         if (is_master() || is_monitor() || is_hidden()) {
708                 return;
709         }
710
711         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_solo()) {
712                 _route_group->apply (&Route::set_solo_isolated, yn, _route_group);
713                 return;
714         }
715         
716         /* forward propagate solo-isolate status to everything fed by this route, but not those via sends only */
717
718         boost::shared_ptr<RouteList> routes = _session.get_routes ();
719         for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
720
721                 if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
722                         continue;
723                 }
724
725                 bool sends_only;
726                 bool does_feed = direct_feeds (*i, &sends_only); // we will recurse anyway, so don't use ::feeds()
727                 
728                 if (does_feed && !sends_only) {
729                         (*i)->set_solo_isolated (yn, (*i)->route_group());
730                 }
731         }
732
733         /* XXX should we back-propagate as well? (April 2010: myself and chris goddard think not) */
734
735         bool changed = false;
736
737         if (yn) {
738                 if (_solo_isolated == 0) {
739                         _mute_master->set_solo_ignore (true);
740                         changed = true;
741                 }
742                 _solo_isolated++;
743         } else {
744                 if (_solo_isolated > 0) {
745                         _solo_isolated--;
746                         if (_solo_isolated == 0) {
747                                 _mute_master->set_solo_ignore (false);
748                                 changed = true;
749                         }
750                 }
751         }
752
753         if (changed) {
754                 solo_isolated_changed (src);
755         }
756 }
757
758 bool
759 Route::solo_isolated () const
760 {
761         return _solo_isolated > 0;
762 }
763
764 void
765 Route::set_mute_points (MuteMaster::MutePoint mp)
766 {
767         _mute_master->set_mute_points (mp);
768         mute_points_changed (); /* EMIT SIGNAL */
769         
770         if (_mute_master->muted_by_self()) {
771                 mute_changed (this); /* EMIT SIGNAL */
772         }
773 }
774
775 void
776 Route::set_mute (bool yn, void *src)
777 {
778         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_mute()) {
779                 _route_group->apply (&Route::set_mute, yn, _route_group);
780                 return;
781         }
782
783         if (muted() != yn) {
784                 _mute_master->set_muted_by_self (yn);
785                 mute_changed (src); /* EMIT SIGNAL */
786         }
787 }
788
789 bool
790 Route::muted () const
791 {
792         return _mute_master->muted_by_self();
793 }
794
795 #if 0
796 static void
797 dump_processors(const string& name, const list<boost::shared_ptr<Processor> >& procs)
798 {
799         cerr << name << " {" << endl;
800         for (list<boost::shared_ptr<Processor> >::const_iterator p = procs.begin();
801                         p != procs.end(); ++p) {
802                 cerr << "\t" << (*p)->name() << " ID = " << (*p)->id() << endl;
803         }
804         cerr << "}" << endl;
805 }
806 #endif
807
808 int
809 Route::add_processor (boost::shared_ptr<Processor> processor, Placement placement, ProcessorStreams* err)
810 {
811         ProcessorList::iterator loc;
812
813         /* XXX this is not thread safe - we don't hold the lock across determining the iter
814            to add before and actually doing the insertion. dammit.
815         */
816
817         if (placement == PreFader) {
818                 /* generic pre-fader: insert immediately before the amp */
819                 loc = find (_processors.begin(), _processors.end(), _amp);
820         } else {
821                 /* generic post-fader: insert right before the main outs */
822                 loc = find (_processors.begin(), _processors.end(), _main_outs);
823         }
824
825         return add_processor (processor, loc, err);
826 }
827
828
829 /** Add a processor to the route.
830  * @a iter must point to an iterator in _processors and the new
831  * processor will be inserted immediately before this location.  Otherwise,
832  * @a position is used.
833  */
834 int
835 Route::add_processor (boost::shared_ptr<Processor> processor, ProcessorList::iterator iter, ProcessorStreams* err, bool activation_allowed)
836 {
837         ChanCount old_pms = processor_max_streams;
838
839         if (!_session.engine().connected() || !processor) {
840                 return 1;
841         }
842
843         {
844                 Glib::RWLock::WriterLock lm (_processor_lock);
845
846                 boost::shared_ptr<PluginInsert> pi;
847                 boost::shared_ptr<PortInsert> porti;
848
849                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), processor);
850
851                 if (processor == _amp || processor == _meter || processor == _main_outs) {
852                         // Ensure only one of these are in the list at any time
853                         if (loc != _processors.end()) {
854                                 if (iter == loc) { // Already in place, do nothing
855                                         return 0;
856                                 } else { // New position given, relocate
857                                         _processors.erase (loc);
858                                 }
859                         }
860
861                 } else {
862                         if (loc != _processors.end()) {
863                                 cerr << "ERROR: Processor added to route twice!" << endl;
864                                 return 1;
865                         }
866
867                         loc = iter;
868                 }
869
870                 _processors.insert (loc, processor);
871
872                 // Set up processor list channels.  This will set processor->[input|output]_streams(),
873                 // configure redirect ports properly, etc.
874
875                 if (configure_processors_unlocked (err)) {
876                         ProcessorList::iterator ploc = loc;
877                         --ploc;
878                         _processors.erase(ploc);
879                         configure_processors_unlocked (0); // it worked before we tried to add it ...
880                         cerr << "configure failed\n";
881                         return -1;
882                 }
883
884                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(processor)) != 0) {
885
886                         if (pi->natural_input_streams() == ChanCount::ZERO) {
887                                 /* generator plugin */
888                                 _have_internal_generator = true;
889                         }
890
891                 }
892
893                 /* is this the monitor send ? if so, make sure we keep track of it */
894
895                 boost::shared_ptr<InternalSend> isend = boost::dynamic_pointer_cast<InternalSend> (processor);
896
897                 if (isend && _session.monitor_out() && (isend->target_id() == _session.monitor_out()->id())) {
898                         _monitor_send = isend;
899                 }
900
901                 if (activation_allowed && (processor != _monitor_send)) {
902                         processor->activate ();
903                 }
904
905                 processor->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false, false));
906
907                 _output->set_user_latency (0);
908         }
909
910         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
911         set_processor_positions ();
912
913         return 0;
914 }
915
916 bool
917 Route::add_processor_from_xml_2X (const XMLNode& node, int version, ProcessorList::iterator iter)
918 {
919         const XMLProperty *prop;
920
921         try {
922                 boost::shared_ptr<Processor> processor;
923
924                 if (node.name() == "Insert") {
925
926                         if ((prop = node.property ("type")) != 0) {
927
928                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || 
929                                                 prop->value() == "lv2" ||
930                                                 prop->value() == "vst" ||
931                                                 prop->value() == "audiounit") {
932
933                                         processor.reset (new PluginInsert (_session));
934
935                                 } else {
936
937                                         processor.reset (new PortInsert (_session, _mute_master));
938                                 }
939
940                         }
941
942                 } else if (node.name() == "Send") {
943
944                         processor.reset (new Send (_session, _mute_master));
945
946                 } else {
947
948                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), node.name()) << endmsg;
949                         return false;
950                 }
951
952                 if (processor->set_state (node, version)) {
953                         return false;
954                 }
955
956                 if (iter == _processors.end() && processor->display_to_user() && !_processors.empty()) {
957                         /* check for invisible processors stacked at the end and leave them there */
958                         ProcessorList::iterator p;
959                         p = _processors.end();
960                         --p;
961                         while (!(*p)->display_to_user() && p != _processors.begin()) {
962                                 --p;
963                         }
964                         ++p;
965                         iter = p;
966                 }
967
968                 return (add_processor (processor, iter) == 0);
969         }
970
971         catch (failed_constructor &err) {
972                 warning << _("processor could not be created. Ignored.") << endmsg;
973                 return false;
974         }
975 }
976
977 int
978 Route::add_processors (const ProcessorList& others, boost::shared_ptr<Processor> before, ProcessorStreams* err)
979 {
980         ProcessorList::iterator loc;
981
982         if (before) {
983                 loc = find(_processors.begin(), _processors.end(), before);
984         } else {
985                 /* nothing specified - at end but before main outs */
986                 loc = find (_processors.begin(), _processors.end(), _main_outs);
987         }
988
989         return add_processors (others, loc, err);
990 }
991
992 int
993 Route::add_processors (const ProcessorList& others, ProcessorList::iterator iter, ProcessorStreams* err)
994 {
995         /* NOTE: this is intended to be used ONLY when copying
996            processors from another Route. Hence the subtle
997            differences between this and ::add_processor()
998         */
999
1000         ChanCount old_pms = processor_max_streams;
1001
1002         if (!_session.engine().connected()) {
1003                 return 1;
1004         }
1005
1006         if (others.empty()) {
1007                 return 0;
1008         }
1009
1010         {
1011                 Glib::RWLock::WriterLock lm (_processor_lock);
1012
1013                 ChanCount potential_max_streams = ChanCount::max (_input->n_ports(), _output->n_ports());
1014
1015                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
1016
1017                         // Ensure meter only appears in the list once
1018                         if (*i == _meter) {
1019                                 ProcessorList::iterator m = find(_processors.begin(), _processors.end(), *i);
1020                                 if (m != _processors.end()) {
1021                                         _processors.erase(m);
1022                                 }
1023                         }
1024
1025                         boost::shared_ptr<PluginInsert> pi;
1026
1027                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1028                                 pi->set_count (1);
1029
1030                                 ChanCount m = max (pi->input_streams(), pi->output_streams());
1031
1032                                 if (m > potential_max_streams) {
1033                                         potential_max_streams = m;
1034                                 }
1035                         }
1036
1037                         ProcessorList::iterator inserted = _processors.insert (iter, *i);
1038
1039                         if ((*i)->active()) {
1040                                 (*i)->activate ();
1041                         }
1042
1043                         if (configure_processors_unlocked (err)) {
1044                                 _processors.erase (inserted);
1045                                 configure_processors_unlocked (0); // it worked before we tried to add it ...
1046                                 return -1;
1047                         }
1048
1049                         (*i)->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false, false));
1050                 }
1051
1052                 _output->set_user_latency (0);
1053         }
1054
1055         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1056         set_processor_positions ();
1057
1058         return 0;
1059 }
1060
1061 void
1062 Route::placement_range(Placement p, ProcessorList::iterator& start, ProcessorList::iterator& end)
1063 {
1064         if (p == PreFader) {
1065                 start = _processors.begin();
1066                 end = find(_processors.begin(), _processors.end(), _amp);
1067         } else {
1068                 start = find(_processors.begin(), _processors.end(), _amp);
1069                 ++start;
1070                 end = _processors.end();
1071         }
1072 }
1073
1074 /** Turn off all processors with a given placement
1075  * @param p Placement of processors to disable
1076  */
1077 void
1078 Route::disable_processors (Placement p)
1079 {
1080         Glib::RWLock::ReaderLock lm (_processor_lock);
1081
1082         ProcessorList::iterator start, end;
1083         placement_range(p, start, end);
1084
1085         for (ProcessorList::iterator i = start; i != end; ++i) {
1086                 (*i)->deactivate ();
1087         }
1088
1089         _session.set_dirty ();
1090 }
1091
1092 /** Turn off all redirects
1093  */
1094 void
1095 Route::disable_processors ()
1096 {
1097         Glib::RWLock::ReaderLock lm (_processor_lock);
1098
1099         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1100                 (*i)->deactivate ();
1101         }
1102
1103         _session.set_dirty ();
1104 }
1105
1106 /** Turn off all redirects with a given placement
1107  * @param p Placement of redirects to disable
1108  */
1109 void
1110 Route::disable_plugins (Placement p)
1111 {
1112         Glib::RWLock::ReaderLock lm (_processor_lock);
1113
1114         ProcessorList::iterator start, end;
1115         placement_range(p, start, end);
1116
1117         for (ProcessorList::iterator i = start; i != end; ++i) {
1118                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1119                         (*i)->deactivate ();
1120                 }
1121         }
1122
1123         _session.set_dirty ();
1124 }
1125
1126 /** Turn off all plugins
1127  */
1128 void
1129 Route::disable_plugins ()
1130 {
1131         Glib::RWLock::ReaderLock lm (_processor_lock);
1132
1133         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1134                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1135                         (*i)->deactivate ();
1136                 }
1137         }
1138
1139         _session.set_dirty ();
1140 }
1141
1142
1143 void
1144 Route::ab_plugins (bool forward)
1145 {
1146         Glib::RWLock::ReaderLock lm (_processor_lock);
1147
1148         if (forward) {
1149
1150                 /* forward = turn off all active redirects, and mark them so that the next time
1151                    we go the other way, we will revert them
1152                 */
1153
1154                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1155                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1156                                 continue;
1157                         }
1158
1159                         if ((*i)->active()) {
1160                                 (*i)->deactivate ();
1161                                 (*i)->set_next_ab_is_active (true);
1162                         } else {
1163                                 (*i)->set_next_ab_is_active (false);
1164                         }
1165                 }
1166
1167         } else {
1168
1169                 /* backward = if the redirect was marked to go active on the next ab, do so */
1170
1171                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1172
1173                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1174                                 continue;
1175                         }
1176
1177                         if ((*i)->get_next_ab_is_active()) {
1178                                 (*i)->activate ();
1179                         } else {
1180                                 (*i)->deactivate ();
1181                         }
1182                 }
1183         }
1184
1185         _session.set_dirty ();
1186 }
1187
1188
1189 /** Remove processors with a given placement.
1190  * @param p Placement of processors to remove.
1191  */
1192 void
1193 Route::clear_processors (Placement p)
1194 {
1195         const ChanCount old_pms = processor_max_streams;
1196
1197         if (!_session.engine().connected()) {
1198                 return;
1199         }
1200
1201         bool already_deleting = _session.deletion_in_progress();
1202         if (!already_deleting) {
1203                 _session.set_deletion_in_progress();
1204         }
1205
1206         {
1207                 Glib::RWLock::WriterLock lm (_processor_lock);
1208                 ProcessorList new_list;
1209                 ProcessorStreams err;
1210                 bool seen_amp = false;
1211
1212                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1213
1214                         if (*i == _amp) {
1215                                 seen_amp = true;
1216                         }
1217
1218                         if ((*i) == _amp || (*i) == _meter || (*i) == _main_outs) {
1219
1220                                 /* you can't remove these */
1221
1222                                 new_list.push_back (*i);
1223
1224                         } else {
1225                                 if (seen_amp) {
1226
1227                                         switch (p) {
1228                                         case PreFader:
1229                                                 new_list.push_back (*i);
1230                                                 break;
1231                                         case PostFader:
1232                                                 (*i)->drop_references ();
1233                                                 break;
1234                                         }
1235
1236                                 } else {
1237
1238                                         switch (p) {
1239                                         case PreFader:
1240                                                 (*i)->drop_references ();
1241                                                 break;
1242                                         case PostFader:
1243                                                 new_list.push_back (*i);
1244                                                 break;
1245                                         }
1246                                 }
1247                         }
1248                 }
1249
1250                 _processors = new_list;
1251                 configure_processors_unlocked (&err); // this can't fail
1252         }
1253
1254         processor_max_streams.reset();
1255         _have_internal_generator = false;
1256         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1257         set_processor_positions ();
1258
1259         if (!already_deleting) {
1260                 _session.clear_deletion_in_progress();
1261         }
1262 }
1263
1264 int
1265 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err)
1266 {
1267         /* these can never be removed */
1268
1269         if (processor == _amp || processor == _meter || processor == _main_outs) {
1270                 return 0;
1271         }
1272
1273         ChanCount old_pms = processor_max_streams;
1274
1275         if (!_session.engine().connected()) {
1276                 return 1;
1277         }
1278
1279         processor_max_streams.reset();
1280
1281         {
1282                 Glib::RWLock::WriterLock lm (_processor_lock);
1283                 ProcessorList::iterator i;
1284                 bool removed = false;
1285
1286                 for (i = _processors.begin(); i != _processors.end(); ) {
1287                         if (*i == processor) {
1288
1289                                 /* move along, see failure case for configure_processors()
1290                                    where we may need to reconfigure the processor.
1291                                 */
1292
1293                                 /* stop redirects that send signals to JACK ports
1294                                    from causing noise as a result of no longer being
1295                                    run.
1296                                 */
1297
1298                                 boost::shared_ptr<IOProcessor> iop;
1299
1300                                 if ((iop = boost::dynamic_pointer_cast<IOProcessor> (*i)) != 0) {
1301                                         if (iop->input()) {
1302                                                 iop->input()->disconnect (this);
1303                                         }
1304                                         if (iop->output()) {
1305                                                 iop->output()->disconnect (this);
1306                                         }
1307                                 }
1308
1309                                 i = _processors.erase (i);
1310                                 removed = true;
1311                                 break;
1312
1313                         } else {
1314                                 ++i;
1315                         }
1316
1317                         _output->set_user_latency (0);
1318                 }
1319
1320                 if (!removed) {
1321                         /* what? */
1322                         return 1;
1323                 }
1324
1325                 if (configure_processors_unlocked (err)) {
1326                         /* get back to where we where */
1327                         _processors.insert (i, processor);
1328                         /* we know this will work, because it worked before :) */
1329                         configure_processors_unlocked (0);
1330                         return -1;
1331                 }
1332
1333                 _have_internal_generator = false;
1334
1335                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1336                         boost::shared_ptr<PluginInsert> pi;
1337
1338                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1339                                 if (pi->is_generator()) {
1340                                         _have_internal_generator = true;
1341                                         break;
1342                                 }
1343                         }
1344                 }
1345         }
1346
1347         processor->drop_references ();
1348         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1349         set_processor_positions ();
1350
1351         return 0;
1352 }
1353
1354 int
1355 Route::remove_processors (const ProcessorList& to_be_deleted, ProcessorStreams* err)
1356 {
1357         ProcessorList deleted;
1358
1359         if (!_session.engine().connected()) {
1360                 return 1;
1361         }
1362
1363         processor_max_streams.reset();
1364
1365         {
1366                 Glib::RWLock::WriterLock lm (_processor_lock);
1367                 ProcessorList::iterator i;
1368                 boost::shared_ptr<Processor> processor;
1369
1370                 ProcessorList as_we_were = _processors;
1371
1372                 for (i = _processors.begin(); i != _processors.end(); ) {
1373
1374                         processor = *i;
1375
1376                         /* these can never be removed */
1377
1378                         if (processor == _amp || processor == _meter || processor == _main_outs) {
1379                                 ++i;
1380                                 continue;
1381                         }
1382
1383                         /* see if its in the list of processors to delete */
1384
1385                         if (find (to_be_deleted.begin(), to_be_deleted.end(), processor) == to_be_deleted.end()) {
1386                                 ++i;
1387                                 continue;
1388                         }
1389
1390                         /* stop IOProcessors that send to JACK ports
1391                            from causing noise as a result of no longer being
1392                            run.
1393                         */
1394
1395                         boost::shared_ptr<IOProcessor> iop;
1396
1397                         if ((iop = boost::dynamic_pointer_cast<IOProcessor> (processor)) != 0) {
1398                                 iop->disconnect ();
1399                         }
1400
1401                         deleted.push_back (processor);
1402                         i = _processors.erase (i);
1403                 }
1404
1405                 if (deleted.empty()) {
1406                         /* none of those in the requested list were found */
1407                         return 0;
1408                 }
1409
1410                 _output->set_user_latency (0);
1411
1412                 if (configure_processors_unlocked (err)) {
1413                         /* get back to where we where */
1414                         _processors = as_we_were;
1415                         /* we know this will work, because it worked before :) */
1416                         configure_processors_unlocked (0);
1417                         return -1;
1418                 }
1419
1420                 _have_internal_generator = false;
1421
1422                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1423                         boost::shared_ptr<PluginInsert> pi;
1424
1425                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1426                                 if (pi->is_generator()) {
1427                                         _have_internal_generator = true;
1428                                         break;
1429                                 }
1430                         }
1431                 }
1432         }
1433
1434         /* now try to do what we need to so that those that were removed will be deleted */
1435
1436         for (ProcessorList::iterator i = deleted.begin(); i != deleted.end(); ++i) {
1437                 (*i)->drop_references ();
1438         }
1439
1440         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1441         set_processor_positions ();
1442
1443         return 0;
1444 }
1445
1446
1447 int
1448 Route::configure_processors (ProcessorStreams* err)
1449 {
1450         if (!_in_configure_processors) {
1451                 Glib::RWLock::WriterLock lm (_processor_lock);
1452                 return configure_processors_unlocked (err);
1453         }
1454         return 0;
1455 }
1456
1457 ChanCount
1458 Route::input_streams () const
1459 {
1460         return _input->n_ports ();
1461 }
1462
1463 /** Configure the input/output configuration of each processor in the processors list.
1464  * Return 0 on success, otherwise configuration is impossible.
1465  */
1466 int
1467 Route::configure_processors_unlocked (ProcessorStreams* err)
1468 {
1469         if (_in_configure_processors) {
1470            return 0;
1471         }
1472
1473         _in_configure_processors = true;
1474
1475         // Check each processor in order to see if we can configure as requested
1476         ChanCount in = input_streams ();
1477         ChanCount out;
1478         list< pair<ChanCount,ChanCount> > configuration;
1479         uint32_t index = 0;
1480
1481         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configure processors\n", _name));
1482         DEBUG_TRACE (DEBUG::Processors, "{\n");
1483         for (list<boost::shared_ptr<Processor> >::const_iterator p = _processors.begin(); p != _processors.end(); ++p) {
1484                 DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1 ID = %2\n", (*p)->name(), (*p)->id()));
1485         }
1486         DEBUG_TRACE (DEBUG::Processors, "}\n");
1487
1488         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++index) {
1489
1490                 if ((*p)->can_support_io_configuration(in, out)) {
1491                         DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1 in = %2 out = %3\n",(*p)->name(), in, out));
1492                         configuration.push_back(make_pair(in, out));
1493                         in = out;
1494                 } else {
1495                         if (err) {
1496                                 err->index = index;
1497                                 err->count = in;
1498                         }
1499                         _in_configure_processors = false;
1500                         return -1;
1501                 }
1502         }
1503
1504         // We can, so configure everything
1505         list< pair<ChanCount,ChanCount> >::iterator c = configuration.begin();
1506         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++c) {
1507                 (*p)->configure_io(c->first, c->second);
1508                 processor_max_streams = ChanCount::max(processor_max_streams, c->first);
1509                 processor_max_streams = ChanCount::max(processor_max_streams, c->second);
1510                 out = c->second;
1511         }
1512
1513         if (_meter) {
1514                 _meter->reset_max_channels (processor_max_streams);
1515         }
1516
1517         /* make sure we have sufficient scratch buffers to cope with the new processor
1518            configuration */
1519         {
1520                 Glib::Mutex::Lock em (_session.engine().process_lock ());
1521                 _session.ensure_buffers (n_process_buffers ());
1522         }
1523
1524         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configuration complete\n", _name));
1525
1526         _in_configure_processors = false;
1527         return 0;
1528 }
1529
1530 void
1531 Route::all_processors_flip ()
1532 {
1533         Glib::RWLock::ReaderLock lm (_processor_lock);
1534
1535         if (_processors.empty()) {
1536                 return;
1537         }
1538
1539         bool first_is_on = _processors.front()->active();
1540
1541         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1542                 if (first_is_on) {
1543                         (*i)->deactivate ();
1544                 } else {
1545                         (*i)->activate ();
1546                 }
1547         }
1548
1549         _session.set_dirty ();
1550 }
1551
1552 /** Set all processors with a given placement to a given active state.
1553  * @param p Placement of processors to change.
1554  * @param state New active state for those processors.
1555  */
1556 void
1557 Route::all_processors_active (Placement p, bool state)
1558 {
1559         Glib::RWLock::ReaderLock lm (_processor_lock);
1560
1561         if (_processors.empty()) {
1562                 return;
1563         }
1564         ProcessorList::iterator start, end;
1565         placement_range(p, start, end);
1566
1567         bool before_amp = true;
1568         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1569                 if ((*i) == _amp) {
1570                         before_amp = false;
1571                         continue;
1572                 }
1573                 if (p == PreFader && before_amp) {
1574                         if (state) {
1575                                 (*i)->activate ();
1576                         } else {
1577                                 (*i)->deactivate ();
1578                         }
1579                 }
1580         }
1581
1582         _session.set_dirty ();
1583 }
1584
1585 bool
1586 Route::processor_is_prefader (boost::shared_ptr<Processor> p)
1587 {
1588         bool pre_fader = true;
1589         Glib::RWLock::ReaderLock lm (_processor_lock);
1590
1591         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1592
1593                 /* semantic note: if p == amp, we want to return true, so test
1594                    for equality before checking if this is the amp
1595                 */
1596
1597                 if ((*i) == p) {
1598                         break;
1599                 }
1600
1601                 if ((*i) == _amp) {
1602                         pre_fader = false;
1603                         break;
1604                 }
1605         }
1606
1607         return pre_fader;
1608 }
1609
1610 int
1611 Route::reorder_processors (const ProcessorList& new_order, ProcessorStreams* err)
1612 {
1613         /* "new_order" is an ordered list of processors to be positioned according to "placement".
1614            NOTE: all processors in "new_order" MUST be marked as display_to_user(). There maybe additional
1615            processors in the current actual processor list that are hidden. Any visible processors
1616            in the current list but not in "new_order" will be assumed to be deleted.
1617         */
1618
1619         {
1620                 Glib::RWLock::WriterLock lm (_processor_lock);
1621                 ChanCount old_pms = processor_max_streams;
1622                 ProcessorList::iterator oiter;
1623                 ProcessorList::const_iterator niter;
1624                 ProcessorList as_it_was_before = _processors;
1625                 ProcessorList as_it_will_be;
1626
1627                 oiter = _processors.begin();
1628                 niter = new_order.begin();
1629
1630                 while (niter !=  new_order.end()) {
1631
1632                         /* if the next processor in the old list is invisible (i.e. should not be in the new order)
1633                            then append it to the temp list.
1634
1635                            Otherwise, see if the next processor in the old list is in the new list. if not,
1636                            its been deleted. If its there, append it to the temp list.
1637                         */
1638
1639                         if (oiter == _processors.end()) {
1640
1641                                 /* no more elements in the old list, so just stick the rest of
1642                                    the new order onto the temp list.
1643                                 */
1644
1645                                 as_it_will_be.insert (as_it_will_be.end(), niter, new_order.end());
1646                                 while (niter != new_order.end()) {
1647                                         ++niter;
1648                                 }
1649                                 break;
1650
1651                         } else {
1652
1653                                 if (!(*oiter)->display_to_user()) {
1654
1655                                         as_it_will_be.push_back (*oiter);
1656
1657                                 } else {
1658
1659                                         /* visible processor: check that its in the new order */
1660
1661                                         if (find (new_order.begin(), new_order.end(), (*oiter)) == new_order.end()) {
1662                                                 /* deleted: do nothing, shared_ptr<> will clean up */
1663                                         } else {
1664                                                 /* ignore this one, and add the next item from the new order instead */
1665                                                 as_it_will_be.push_back (*niter);
1666                                                 ++niter;
1667                                         }
1668                                 }
1669
1670                                 /* now remove from old order - its taken care of no matter what */
1671                                 oiter = _processors.erase (oiter);
1672                         }
1673
1674                 }
1675
1676                 _processors.insert (oiter, as_it_will_be.begin(), as_it_will_be.end());
1677
1678                 if (configure_processors_unlocked (err)) {
1679                         _processors = as_it_was_before;
1680                         processor_max_streams = old_pms;
1681                         return -1;
1682                 }
1683         }
1684
1685         if (true) {
1686                 processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1687                 set_processor_positions ();
1688         }
1689
1690         return 0;
1691 }
1692
1693 XMLNode&
1694 Route::get_state()
1695 {
1696         return state(true);
1697 }
1698
1699 XMLNode&
1700 Route::get_template()
1701 {
1702         return state(false);
1703 }
1704
1705 XMLNode&
1706 Route::state(bool full_state)
1707 {
1708         XMLNode *node = new XMLNode("Route");
1709         ProcessorList::iterator i;
1710         char buf[32];
1711
1712         id().print (buf, sizeof (buf));
1713         node->add_property("id", buf);
1714         node->add_property ("name", _name);
1715         node->add_property("default-type", _default_type.to_string());
1716
1717         if (_flags) {
1718                 node->add_property("flags", enum_2_string (_flags));
1719         }
1720
1721         node->add_property("active", _active?"yes":"no");
1722         string p;
1723         boost::to_string (_phase_invert, p);
1724         node->add_property("phase-invert", p);
1725         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
1726         node->add_property("meter-point", enum_2_string (_meter_point));
1727
1728         if (_route_group) {
1729                 node->add_property("route-group", _route_group->name());
1730         }
1731
1732         string order_string;
1733         OrderKeys::iterator x = order_keys.begin();
1734
1735         while (x != order_keys.end()) {
1736                 order_string += string ((*x).first);
1737                 order_string += '=';
1738                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1739                 order_string += buf;
1740
1741                 ++x;
1742
1743                 if (x == order_keys.end()) {
1744                         break;
1745                 }
1746
1747                 order_string += ':';
1748         }
1749         node->add_property ("order-keys", order_string);
1750         node->add_property ("self-solo", (_self_solo ? "yes" : "no"));
1751         snprintf (buf, sizeof (buf), "%d", _soloed_by_others_upstream);
1752         node->add_property ("soloed-by-upstream", buf);
1753         snprintf (buf, sizeof (buf), "%d", _soloed_by_others_downstream);
1754         node->add_property ("soloed-by-downstream", buf);
1755
1756         node->add_child_nocopy (_input->state (full_state));
1757         node->add_child_nocopy (_output->state (full_state));
1758         node->add_child_nocopy (_solo_control->get_state ());
1759         node->add_child_nocopy (_mute_master->get_state ());
1760
1761         XMLNode* remote_control_node = new XMLNode (X_("RemoteControl"));
1762         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1763         remote_control_node->add_property (X_("id"), buf);
1764         node->add_child_nocopy (*remote_control_node);
1765
1766         if (_comment.length()) {
1767                 XMLNode *cmt = node->add_child ("Comment");
1768                 cmt->add_content (_comment);
1769         }
1770
1771         for (i = _processors.begin(); i != _processors.end(); ++i) {
1772                 node->add_child_nocopy((*i)->state (full_state));
1773         }
1774
1775         if (_extra_xml){
1776                 node->add_child_copy (*_extra_xml);
1777         }
1778
1779         return *node;
1780 }
1781
1782 int
1783 Route::set_state (const XMLNode& node, int version)
1784 {
1785         return _set_state (node, version, true);
1786 }
1787
1788 int
1789 Route::_set_state (const XMLNode& node, int version, bool /*call_base*/)
1790 {
1791         if (version < 3000) {
1792                 return _set_state_2X (node, version);
1793         }
1794
1795         XMLNodeList nlist;
1796         XMLNodeConstIterator niter;
1797         XMLNode *child;
1798         XMLPropertyList plist;
1799         const XMLProperty *prop;
1800
1801         if (node.name() != "Route"){
1802                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1803                 return -1;
1804         }
1805
1806         if ((prop = node.property (X_("name"))) != 0) {
1807                 Route::set_name (prop->value());
1808         }
1809
1810         if ((prop = node.property ("id")) != 0) {
1811                 _id = prop->value ();
1812         }
1813
1814         if ((prop = node.property (X_("flags"))) != 0) {
1815                 _flags = Flag (string_2_enum (prop->value(), _flags));
1816         } else {
1817                 _flags = Flag (0);
1818         }
1819
1820         if (is_master() || is_monitor() || is_hidden()) {
1821                 _mute_master->set_solo_ignore (true);
1822         }
1823
1824         /* add all processors (except amp, which is always present) */
1825
1826         nlist = node.children();
1827         XMLNode processor_state (X_("processor_state"));
1828
1829         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1830
1831                 child = *niter;
1832
1833                 if (child->name() == IO::state_node_name) {
1834                         if ((prop = child->property (X_("direction"))) == 0) {
1835                                 continue;
1836                         }
1837
1838                         if (prop->value() == "Input") {
1839                                 _input->set_state (*child, version);
1840                         } else if (prop->value() == "Output") {
1841                                 _output->set_state (*child, version);
1842                         }
1843                 }
1844
1845                 if (child->name() == X_("Processor")) {
1846                         processor_state.add_child_copy (*child);
1847                 }
1848         }
1849
1850         set_processor_state (processor_state);
1851
1852         if ((prop = node.property ("self-solo")) != 0) {
1853                 set_self_solo (string_is_affirmative (prop->value()));
1854         }
1855
1856         if ((prop = node.property ("soloed-by-upstream")) != 0) {
1857                 _soloed_by_others_upstream = 0; // needed for mod_.... () to work
1858                 mod_solo_by_others_upstream (atoi (prop->value()));
1859         }
1860
1861         if ((prop = node.property ("soloed-by-downstream")) != 0) {
1862                 _soloed_by_others_downstream = 0; // needed for mod_.... () to work
1863                 mod_solo_by_others_downstream (atoi (prop->value()));
1864         }
1865
1866         if ((prop = node.property ("solo-isolated")) != 0) {
1867                 set_solo_isolated (string_is_affirmative (prop->value()), this);
1868         }
1869
1870         if ((prop = node.property (X_("phase-invert"))) != 0) {
1871                 set_phase_invert (boost::dynamic_bitset<> (prop->value ()));
1872         }
1873
1874         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1875                 set_denormal_protection (string_is_affirmative (prop->value()));
1876         }
1877
1878         if ((prop = node.property (X_("active"))) != 0) {
1879                 bool yn = string_is_affirmative (prop->value());
1880                 _active = !yn; // force switch
1881                 set_active (yn);
1882         }
1883
1884         if ((prop = node.property (X_("meter-point"))) != 0) {
1885                 MeterPoint mp = MeterPoint (string_2_enum (prop->value (), _meter_point));
1886                 set_meter_point (mp);
1887                 if (_meter) {
1888                         _meter->set_display_to_user (_meter_point == MeterCustom);
1889                 }
1890         }
1891
1892         if ((prop = node.property (X_("order-keys"))) != 0) {
1893
1894                 int32_t n;
1895
1896                 string::size_type colon, equal;
1897                 string remaining = prop->value();
1898
1899                 while (remaining.length()) {
1900
1901                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1902                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1903                                       << endmsg;
1904                         } else {
1905                                 if (sscanf (remaining.substr (equal+1).c_str(), "%d", &n) != 1) {
1906                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1907                                               << endmsg;
1908                                 } else {
1909                                         set_order_key (remaining.substr (0, equal), n);
1910                                 }
1911                         }
1912
1913                         colon = remaining.find_first_of (':');
1914
1915                         if (colon != string::npos) {
1916                                 remaining = remaining.substr (colon+1);
1917                         } else {
1918                                 break;
1919                         }
1920                 }
1921         }
1922
1923         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1924                 child = *niter;
1925
1926                 if (child->name() == X_("Comment")) {
1927
1928                         /* XXX this is a terrible API design in libxml++ */
1929
1930                         XMLNode *cmt = *(child->children().begin());
1931                         _comment = cmt->content();
1932
1933                 } else if (child->name() == X_("Extra")) {
1934
1935                         _extra_xml = new XMLNode (*child);
1936
1937                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
1938
1939                         if (prop->value() == "solo") {
1940                                 _solo_control->set_state (*child, version);
1941                                 _session.add_controllable (_solo_control);
1942                         }
1943
1944                 } else if (child->name() == X_("RemoteControl")) {
1945                         if ((prop = child->property (X_("id"))) != 0) {
1946                                 int32_t x;
1947                                 sscanf (prop->value().c_str(), "%d", &x);
1948                                 set_remote_control_id (x);
1949                         }
1950
1951                 } else if (child->name() == X_("MuteMaster")) {
1952                         _mute_master->set_state (*child, version);
1953                 }
1954         }
1955
1956         return 0;
1957 }
1958
1959 int
1960 Route::_set_state_2X (const XMLNode& node, int version)
1961 {
1962         XMLNodeList nlist;
1963         XMLNodeConstIterator niter;
1964         XMLNode *child;
1965         XMLPropertyList plist;
1966         const XMLProperty *prop;
1967
1968         /* 2X things which still remain to be handled:
1969          * default-type
1970          * automation
1971          * controlouts
1972          */
1973
1974         if (node.name() != "Route") {
1975                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1976                 return -1;
1977         }
1978
1979         if ((prop = node.property (X_("flags"))) != 0) {
1980                 _flags = Flag (string_2_enum (prop->value(), _flags));
1981         } else {
1982                 _flags = Flag (0);
1983         }
1984         
1985         if ((prop = node.property (X_("phase-invert"))) != 0) {
1986                 boost::dynamic_bitset<> p (_input->n_ports().n_audio ());
1987                 if (string_is_affirmative (prop->value ())) {
1988                         p.set ();
1989                 }                       
1990                 set_phase_invert (p);
1991         }
1992
1993         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1994                 set_denormal_protection (string_is_affirmative (prop->value()));
1995         }
1996
1997         if ((prop = node.property (X_("soloed"))) != 0) {
1998                 bool yn = string_is_affirmative (prop->value());
1999
2000                 /* XXX force reset of solo status */
2001
2002                 set_solo (yn, this);
2003         }
2004
2005         if ((prop = node.property (X_("muted"))) != 0) {
2006                 
2007                 bool first = true;
2008                 bool muted = string_is_affirmative (prop->value());
2009                 
2010                 if (muted){
2011                   
2012                         string mute_point;
2013                         
2014                         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
2015                           
2016                                 if (string_is_affirmative (prop->value())){
2017                                         mute_point = mute_point + "PreFader";
2018                                         first = false;
2019                                 }
2020                         }
2021                         
2022                         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
2023                           
2024                                 if (string_is_affirmative (prop->value())){
2025                                   
2026                                         if (!first) {
2027                                                 mute_point = mute_point + ",";
2028                                         }
2029                                         
2030                                         mute_point = mute_point + "PostFader";
2031                                         first = false;
2032                                 }
2033                         }
2034
2035                         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
2036                           
2037                                 if (string_is_affirmative (prop->value())){
2038                                   
2039                                         if (!first) {
2040                                                 mute_point = mute_point + ",";
2041                                         }
2042                                         
2043                                         mute_point = mute_point + "Listen";
2044                                         first = false;
2045                                 }
2046                         }
2047
2048                         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
2049                           
2050                                 if (string_is_affirmative (prop->value())){
2051                                   
2052                                         if (!first) {
2053                                                 mute_point = mute_point + ",";
2054                                         }
2055                                         
2056                                         mute_point = mute_point + "Main";
2057                                 }
2058                         }
2059                         
2060                         _mute_master->set_mute_points (mute_point);
2061                 }
2062         }
2063
2064         if ((prop = node.property (X_("meter-point"))) != 0) {
2065                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
2066         }
2067
2068         /* do not carry over edit/mix groups from 2.X because (a) its hard (b) they
2069            don't mean the same thing.
2070         */
2071
2072         if ((prop = node.property (X_("order-keys"))) != 0) {
2073
2074                 int32_t n;
2075
2076                 string::size_type colon, equal;
2077                 string remaining = prop->value();
2078
2079                 while (remaining.length()) {
2080
2081                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
2082                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2083                                         << endmsg;
2084                         } else {
2085                                 if (sscanf (remaining.substr (equal+1).c_str(), "%d", &n) != 1) {
2086                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2087                                                 << endmsg;
2088                                 } else {
2089                                         set_order_key (remaining.substr (0, equal), n);
2090                                 }
2091                         }
2092
2093                         colon = remaining.find_first_of (':');
2094
2095                         if (colon != string::npos) {
2096                                 remaining = remaining.substr (colon+1);
2097                         } else {
2098                                 break;
2099                         }
2100                 }
2101         }
2102
2103         /* add standard processors */
2104
2105         //_meter.reset (new PeakMeter (_session));
2106         //add_processor (_meter, PreFader);
2107
2108         if (is_monitor()) {
2109                 /* where we listen to tracks */
2110                 _intreturn.reset (new InternalReturn (_session));
2111                 add_processor (_intreturn, PreFader);
2112
2113                 _monitor_control.reset (new MonitorProcessor (_session));
2114                 add_processor (_monitor_control, PostFader);
2115         }
2116
2117         _main_outs.reset (new Delivery (_session, _output, _mute_master, _name, Delivery::Main));
2118         add_processor (_main_outs, PostFader);
2119
2120         /* IOs */
2121
2122         nlist = node.children ();
2123         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2124
2125                 child = *niter;
2126
2127                 if (child->name() == IO::state_node_name) {
2128
2129                         /* there is a note in IO::set_state_2X() about why we have to call
2130                            this directly.
2131                            */
2132
2133                         _input->set_state_2X (*child, version, true);
2134                         _output->set_state_2X (*child, version, false);
2135
2136                         if ((prop = child->property (X_("name"))) != 0) {
2137                                 Route::set_name (prop->value ());
2138                         }
2139
2140                         if ((prop = child->property (X_("id"))) != 0) {
2141                                 _id = prop->value ();
2142                         }
2143
2144                         if ((prop = child->property (X_("active"))) != 0) {
2145                                 bool yn = string_is_affirmative (prop->value());
2146                                 _active = !yn; // force switch
2147                                 set_active (yn);
2148                         }
2149                         
2150                         if ((prop = child->property (X_("gain"))) != 0) {
2151                                 gain_t val;
2152
2153                                 if (sscanf (prop->value().c_str(), "%f", &val) == 1) {
2154                                         _amp->gain_control()->set_value (val);
2155                                 }
2156                         }
2157                         
2158                         /* Set up Panners in the IO */
2159                         XMLNodeList io_nlist = child->children ();
2160                         
2161                         XMLNodeConstIterator io_niter;
2162                         XMLNode *io_child;
2163                         
2164                         for (io_niter = io_nlist.begin(); io_niter != io_nlist.end(); ++io_niter) {
2165
2166                                 io_child = *io_niter;
2167                                 
2168                                 if (io_child->name() == X_("Panner")) {
2169                                         _main_outs->panner()->set_state(*io_child, version);
2170                                 }
2171                         }
2172                 }
2173         }
2174
2175         XMLNodeList redirect_nodes;
2176
2177         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2178
2179                 child = *niter;
2180
2181                 if (child->name() == X_("Send") || child->name() == X_("Insert")) {
2182                         redirect_nodes.push_back(child);
2183                 }
2184
2185         }
2186
2187         set_processor_state_2X (redirect_nodes, version);
2188
2189         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2190                 child = *niter;
2191
2192                 if (child->name() == X_("Comment")) {
2193
2194                         /* XXX this is a terrible API design in libxml++ */
2195
2196                         XMLNode *cmt = *(child->children().begin());
2197                         _comment = cmt->content();
2198
2199                 } else if (child->name() == X_("Extra")) {
2200
2201                         _extra_xml = new XMLNode (*child);
2202
2203                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
2204
2205                         if (prop->value() == "solo") {
2206                                 _solo_control->set_state (*child, version);
2207                                 _session.add_controllable (_solo_control);
2208                         }
2209
2210                 } else if (child->name() == X_("RemoteControl")) {
2211                         if ((prop = child->property (X_("id"))) != 0) {
2212                                 int32_t x;
2213                                 sscanf (prop->value().c_str(), "%d", &x);
2214                                 set_remote_control_id (x);
2215                         }
2216
2217                 } 
2218         }
2219
2220         return 0;
2221 }
2222
2223 XMLNode&
2224 Route::get_processor_state ()
2225 {
2226         XMLNode* root = new XMLNode (X_("redirects"));
2227         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2228                 root->add_child_nocopy ((*i)->state (true));
2229         }
2230
2231         return *root;
2232 }
2233
2234 void
2235 Route::set_processor_state_2X (XMLNodeList const & nList, int version)
2236 {
2237         /* We don't bother removing existing processors not in nList, as this
2238            method will only be called when creating a Route from scratch, not
2239            for undo purposes.  Just put processors in at the appropriate place
2240            in the list.
2241         */
2242
2243         for (XMLNodeConstIterator i = nList.begin(); i != nList.end(); ++i) {
2244                 add_processor_from_xml_2X (**i, version, _processors.begin ());
2245         }
2246 }
2247
2248 void
2249 Route::set_processor_state (const XMLNode& node)
2250 {
2251         const XMLNodeList &nlist = node.children();
2252         XMLNodeConstIterator niter;
2253         ProcessorList new_order;
2254         bool must_configure = false;
2255
2256         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2257
2258                 XMLProperty* prop = (*niter)->property ("type");
2259
2260                 if (prop->value() == "amp") {
2261                         _amp->set_state (**niter, Stateful::current_state_version);
2262                         new_order.push_back (_amp);
2263                 } else if (prop->value() == "meter") {
2264                         _meter->set_state (**niter, Stateful::current_state_version);
2265                         new_order.push_back (_meter);
2266                 } else if (prop->value() == "main-outs") {
2267                         _main_outs->set_state (**niter, Stateful::current_state_version);
2268                         new_order.push_back (_main_outs);
2269                 } else if (prop->value() == "intreturn") {
2270                         if (!_intreturn) {
2271                                 _intreturn.reset (new InternalReturn (_session));
2272                                 must_configure = true;
2273                         }
2274                         _intreturn->set_state (**niter, Stateful::current_state_version);
2275                         new_order.push_back (_intreturn);
2276                 } else if (is_monitor() && prop->value() == "monitor") {
2277                         if (!_monitor_control) {
2278                                 _monitor_control.reset (new MonitorProcessor (_session));
2279                                 must_configure = true;
2280                         }
2281                         _monitor_control->set_state (**niter, Stateful::current_state_version);
2282                         new_order.push_back (_monitor_control);
2283                 } else {
2284                         ProcessorList::iterator o;
2285
2286                         for (o = _processors.begin(); o != _processors.end(); ++o) {
2287                                 XMLProperty* id_prop = (*niter)->property(X_("id"));
2288                                 if (id_prop && (*o)->id() == id_prop->value()) {
2289                                         (*o)->set_state (**niter, Stateful::current_state_version);
2290                                         new_order.push_back (*o);
2291                                         break;
2292                                 }
2293                         }
2294
2295                         // If the processor (*niter) is not on the route then create it 
2296                         
2297                         if (o == _processors.end()) {
2298                                 
2299                                 boost::shared_ptr<Processor> processor;
2300
2301                                 if (prop->value() == "intsend") {
2302                                         
2303                                         processor.reset (new InternalSend (_session, _mute_master, boost::shared_ptr<Route>(), Delivery::Role (0)));
2304                                         
2305                                 } else if (prop->value() == "ladspa" || prop->value() == "Ladspa" ||
2306                                            prop->value() == "lv2" ||
2307                                            prop->value() == "vst" ||
2308                                            prop->value() == "audiounit") {
2309                                         
2310                                         processor.reset (new PluginInsert(_session));
2311                                         
2312                                 } else if (prop->value() == "port") {
2313                                         
2314                                         processor.reset (new PortInsert (_session, _mute_master));
2315                                         
2316                                 } else if (prop->value() == "send") {
2317                                         
2318                                         processor.reset (new Send (_session, _mute_master));
2319                                         
2320                                 } else {
2321                                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
2322                                         continue;
2323                                 }
2324
2325                                 processor->set_state (**niter, Stateful::current_state_version);
2326                                 new_order.push_back (processor);
2327                                 must_configure = true;
2328                         }
2329                 }
2330         }
2331
2332         { 
2333                 Glib::RWLock::WriterLock lm (_processor_lock);
2334                 _processors = new_order;
2335                 if (must_configure) {
2336                         configure_processors_unlocked (0);
2337                 }
2338         }
2339
2340         processors_changed (RouteProcessorChange ());
2341         set_processor_positions ();
2342 }
2343
2344 void
2345 Route::curve_reallocate ()
2346 {
2347 //      _gain_automation_curve.finish_resize ();
2348 //      _pan_automation_curve.finish_resize ();
2349 }
2350
2351 void
2352 Route::silence (nframes_t nframes)
2353 {
2354         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2355         if (!lm.locked()) {
2356                 return;
2357         }
2358
2359         silence_unlocked (nframes);
2360 }
2361
2362 void
2363 Route::silence_unlocked (nframes_t nframes)
2364 {
2365         /* Must be called with the processor lock held */
2366         
2367         if (!_silent) {
2368
2369                 _output->silence (nframes);
2370
2371                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2372                         boost::shared_ptr<PluginInsert> pi;
2373                         
2374                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2375                                 // skip plugins, they don't need anything when we're not active
2376                                 continue;
2377                         }
2378                         
2379                         (*i)->silence (nframes);
2380                 }
2381                 
2382                 if (nframes == _session.get_block_size()) {
2383                         // _silent = true;
2384                 }
2385         }
2386 }
2387
2388 void
2389 Route::add_internal_return ()
2390 {
2391         if (!_intreturn) {
2392                 _intreturn.reset (new InternalReturn (_session));
2393                 add_processor (_intreturn, PreFader);
2394         }
2395 }
2396
2397 BufferSet*
2398 Route::get_return_buffer () const
2399 {
2400         Glib::RWLock::ReaderLock rm (_processor_lock);
2401
2402         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2403                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2404
2405                 if (d) {
2406                         BufferSet* bs = d->get_buffers ();
2407                         return bs;
2408                 }
2409         }
2410
2411         return 0;
2412 }
2413
2414 void
2415 Route::release_return_buffer () const
2416 {
2417         Glib::RWLock::ReaderLock rm (_processor_lock);
2418
2419         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2420                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2421
2422                 if (d) {
2423                         return d->release_buffers ();
2424                 }
2425         }
2426 }
2427
2428 int
2429 Route::listen_via (boost::shared_ptr<Route> route, Placement placement, bool /*active*/, bool aux)
2430 {
2431         vector<string> ports;
2432         vector<string>::const_iterator i;
2433
2434         {
2435                 Glib::RWLock::ReaderLock rm (_processor_lock);
2436
2437                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
2438
2439                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
2440
2441                         if (d && d->target_route() == route) {
2442
2443                                 /* if the target is the control outs, then make sure
2444                                    we take note of which i-send is doing that.
2445                                 */
2446
2447                                 if (route == _session.monitor_out()) {
2448                                         _monitor_send = boost::dynamic_pointer_cast<Delivery>(d);
2449                                 }
2450
2451                                 /* already listening via the specified IO: do nothing */
2452
2453                                 return 0;
2454                         }
2455                 }
2456         }
2457
2458         boost::shared_ptr<InternalSend> listener;
2459
2460         try {
2461
2462                 if (is_master()) {
2463                         
2464                         if (route == _session.monitor_out()) {
2465                                 /* master never sends to control outs */
2466                                 return 0;
2467                         } else {
2468                                 listener.reset (new InternalSend (_session, _mute_master, route, (aux ? Delivery::Aux : Delivery::Listen)));
2469                         }
2470
2471                 } else {
2472                         listener.reset (new InternalSend (_session, _mute_master, route, (aux ? Delivery::Aux : Delivery::Listen)));
2473                 }
2474
2475         } catch (failed_constructor& err) {
2476                 return -1;
2477         }
2478
2479         if (route == _session.monitor_out()) {
2480                 _monitor_send = listener;
2481         }
2482
2483         if (placement == PostFader) {
2484                 /* put it *really* at the end, not just after the panner (main outs)
2485                  */
2486                 add_processor (listener, _processors.end());
2487         } else {
2488                 add_processor (listener, PreFader);
2489         }
2490
2491         return 0;
2492 }
2493
2494 void
2495 Route::drop_listen (boost::shared_ptr<Route> route)
2496 {
2497         ProcessorStreams err;
2498         ProcessorList::iterator tmp;
2499
2500         Glib::RWLock::ReaderLock rl(_processor_lock);
2501         rl.acquire ();
2502
2503   again:
2504         for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ) {
2505
2506                 boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
2507
2508                 if (d && d->target_route() == route) {
2509                         rl.release ();
2510                         remove_processor (*x, &err);
2511                         rl.acquire ();
2512
2513                         /* list could have been demolished while we dropped the lock
2514                            so start over.
2515                         */
2516
2517                         goto again;
2518                 }
2519         }
2520
2521         rl.release ();
2522
2523         if (route == _session.monitor_out()) {
2524                 _monitor_send.reset ();
2525         }
2526 }
2527
2528 void
2529 Route::set_comment (string cmt, void *src)
2530 {
2531         _comment = cmt;
2532         comment_changed (src);
2533         _session.set_dirty ();
2534 }
2535
2536 bool
2537 Route::add_fed_by (boost::shared_ptr<Route> other, bool via_sends_only)
2538 {
2539         FeedRecord fr (other, via_sends_only);
2540
2541         pair<FedBy::iterator,bool> result =  _fed_by.insert (fr);
2542
2543         if (!result.second) {
2544
2545                 /* already a record for "other" - make sure sends-only information is correct */
2546                 if (!via_sends_only && result.first->sends_only) {
2547                         FeedRecord* frp = const_cast<FeedRecord*>(&(*result.first));
2548                         frp->sends_only = false;
2549                 }
2550         }
2551         
2552         return result.second;
2553 }
2554
2555 void
2556 Route::clear_fed_by ()
2557 {
2558         _fed_by.clear ();
2559 }
2560
2561 bool
2562 Route::feeds (boost::shared_ptr<Route> other, bool* via_sends_only)
2563 {
2564         const FedBy& fed_by (other->fed_by());
2565
2566         for (FedBy::iterator f = fed_by.begin(); f != fed_by.end(); ++f) {
2567                 boost::shared_ptr<Route> sr = f->r.lock();
2568
2569                 if (sr && (sr.get() == this)) {
2570
2571                         if (via_sends_only) {
2572                                 *via_sends_only = f->sends_only;
2573                         }
2574
2575                         return true;
2576                 }
2577         }
2578
2579         return false;
2580 }
2581
2582 bool
2583 Route::direct_feeds (boost::shared_ptr<Route> other, bool* only_send)
2584 {
2585         DEBUG_TRACE (DEBUG::Graph, string_compose ("Feeds? %1\n", _name));
2586
2587         if (_output->connected_to (other->input())) {
2588                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\tdirect FEEDS %2\n", other->name()));
2589                 if (only_send) {
2590                         *only_send = false;
2591                 }
2592
2593                 return true;
2594         }
2595
2596         
2597         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); ++r) {
2598
2599                 boost::shared_ptr<IOProcessor> iop;
2600
2601                 if ((iop = boost::dynamic_pointer_cast<IOProcessor>(*r)) != 0) {
2602                         if (iop->feeds (other)) {
2603                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does feed %2\n", iop->name(), other->name()));
2604                                 if (only_send) {
2605                                         *only_send = true;
2606                                 }
2607                                 return true;
2608                         } else {
2609                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does NOT feed %2\n", iop->name(), other->name()));
2610                         }
2611                 } else {
2612                         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tPROC %1 is not an IOP\n", (*r)->name()));
2613                 }
2614                         
2615         }
2616
2617         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tdoes NOT feed %1\n", other->name()));
2618         return false;
2619 }
2620
2621 void
2622 Route::handle_transport_stopped (bool /*abort_ignored*/, bool did_locate, bool can_flush_processors)
2623 {
2624         framepos_t now = _session.transport_frame();
2625
2626         {
2627                 Glib::RWLock::ReaderLock lm (_processor_lock);
2628
2629                 if (!did_locate) {
2630                         automation_snapshot (now, true);
2631                 }
2632
2633                 Automatable::transport_stopped (now);
2634
2635                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2636
2637                         if (Config->get_plugins_stop_with_transport() && can_flush_processors) {
2638                                 (*i)->deactivate ();
2639                                 (*i)->activate ();
2640                                 (*i)->flush ();
2641                         }
2642
2643                         (*i)->transport_stopped (now);
2644                 }
2645         }
2646
2647         _roll_delay = _initial_delay;
2648 }
2649
2650 void
2651 Route::input_change_handler (IOChange change, void * /*src*/)
2652 {
2653         if ((change & ConfigurationChanged)) {
2654                 configure_processors (0);
2655                 _phase_invert.resize (_input->n_ports().n_audio ());
2656                 io_changed (); /* EMIT SIGNAL */
2657         }
2658 }
2659
2660 void
2661 Route::output_change_handler (IOChange change, void * /*src*/)
2662 {
2663         if ((change & ConfigurationChanged)) {
2664
2665                 /* XXX resize all listeners to match _main_outs? */
2666
2667                 // configure_processors (0);
2668         }
2669 }
2670
2671 uint32_t
2672 Route::pans_required () const
2673 {
2674         if (n_outputs().n_audio() < 2) {
2675                 return 0;
2676         }
2677
2678         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
2679 }
2680
2681 int
2682 Route::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame,
2683                 bool session_state_changing, bool /*can_record*/, bool /*rec_monitors_input*/)
2684 {
2685         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2686         if (!lm.locked()) {
2687                 return 0;
2688         }
2689
2690         if (n_outputs().n_total() == 0) {
2691                 return 0;
2692         }
2693
2694         if (!_active || n_inputs() == ChanCount::ZERO)  {
2695                 silence_unlocked (nframes);
2696                 return 0;
2697         }
2698         if (session_state_changing) {
2699                 if (_session.transport_speed() != 0.0f) {
2700                         /* we're rolling but some state is changing (e.g. our diskstream contents)
2701                            so we cannot use them. Be silent till this is over.
2702                            
2703                            XXX note the absurdity of ::no_roll() being called when we ARE rolling!
2704                         */
2705                         silence_unlocked (nframes);
2706                         return 0;
2707                 }
2708                 /* we're really not rolling, so we're either delivery silence or actually
2709                    monitoring, both of which are safe to do while session_state_changing is true.
2710                 */
2711         }
2712
2713         _amp->apply_gain_automation (false);
2714         passthru (start_frame, end_frame, nframes, 0);
2715
2716         return 0;
2717 }
2718
2719 nframes_t
2720 Route::check_initial_delay (nframes_t nframes, nframes_t& transport_frame)
2721 {
2722         if (_roll_delay > nframes) {
2723
2724                 _roll_delay -= nframes;
2725                 silence_unlocked (nframes);
2726                 /* transport frame is not legal for caller to use */
2727                 return 0;
2728
2729         } else if (_roll_delay > 0) {
2730
2731                 nframes -= _roll_delay;
2732                 silence_unlocked (_roll_delay);
2733                 /* we've written _roll_delay of samples into the
2734                    output ports, so make a note of that for
2735                    future reference.
2736                 */
2737                 _main_outs->increment_output_offset (_roll_delay);
2738                 transport_frame += _roll_delay;
2739
2740                 _roll_delay = 0;
2741         }
2742
2743         return nframes;
2744 }
2745
2746 int
2747 Route::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
2748              bool /*can_record*/, bool /*rec_monitors_input*/, bool& /* need_butler */)
2749 {
2750         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2751         if (!lm.locked()) {
2752                 return 0;
2753         }
2754         
2755         automation_snapshot (_session.transport_frame(), false);
2756
2757         if (n_outputs().n_total() == 0) {
2758                 return 0;
2759         }
2760
2761         if (!_active || n_inputs().n_total() == 0) {
2762                 silence_unlocked (nframes);
2763                 return 0;
2764         }
2765
2766         nframes_t unused = 0;
2767
2768         if ((nframes = check_initial_delay (nframes, unused)) == 0) {
2769                 return 0;
2770         }
2771
2772         _silent = false;
2773
2774         passthru (start_frame, end_frame, nframes, declick);
2775
2776         return 0;
2777 }
2778
2779 int
2780 Route::silent_roll (nframes_t nframes, sframes_t /*start_frame*/, sframes_t /*end_frame*/,
2781                     bool /*can_record*/, bool /*rec_monitors_input*/, bool& /* need_butler */)
2782 {
2783         silence (nframes);
2784         return 0;
2785 }
2786
2787 void
2788 Route::toggle_monitor_input ()
2789 {
2790         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end(); ++i) {
2791                 i->ensure_monitor_input( ! i->monitoring_input());
2792         }
2793 }
2794
2795 bool
2796 Route::has_external_redirects () const
2797 {
2798         // FIXME: what about sends? - they don't return a signal back to ardour?
2799
2800         boost::shared_ptr<const PortInsert> pi;
2801
2802         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2803
2804                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2805
2806                         for (PortSet::const_iterator port = pi->output()->ports().begin(); port != pi->output()->ports().end(); ++port) {
2807
2808                                 string port_name = port->name();
2809                                 string client_name = port_name.substr (0, port_name.find(':'));
2810
2811                                 /* only say "yes" if the redirect is actually in use */
2812
2813                                 if (client_name != "ardour" && pi->active()) {
2814                                         return true;
2815                                 }
2816                         }
2817                 }
2818         }
2819
2820         return false;
2821 }
2822
2823 void
2824 Route::flush_processors ()
2825 {
2826         /* XXX shouldn't really try to take this lock, since
2827            this is called from the RT audio thread.
2828         */
2829
2830         Glib::RWLock::ReaderLock lm (_processor_lock);
2831
2832         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2833                 (*i)->flush ();
2834         }
2835 }
2836
2837 void
2838 Route::set_meter_point (MeterPoint p)
2839 {
2840         /* CAN BE CALLED FROM PROCESS CONTEXT */
2841
2842         if (_meter_point == p) {
2843                 return;
2844         }
2845
2846         bool meter_was_visible_to_user = _meter->display_to_user ();
2847
2848         {
2849                 Glib::RWLock::WriterLock lm (_processor_lock);
2850         
2851                 if (p != MeterCustom) {
2852                         // Move meter in the processors list to reflect the new position
2853                         ProcessorList::iterator loc = find (_processors.begin(), _processors.end(), _meter);
2854                         _processors.erase(loc);
2855                         switch (p) {
2856                         case MeterInput:
2857                                 loc = _processors.begin();
2858                                 break;
2859                         case MeterPreFader:
2860                                 loc = find (_processors.begin(), _processors.end(), _amp);
2861                                 break;
2862                         case MeterPostFader:
2863                                 loc = _processors.end();
2864                                 break;
2865                         default:
2866                                 break;
2867                         }
2868                         
2869                         ChanCount m_in;
2870                         
2871                         if (loc == _processors.begin()) {
2872                                 m_in = _input->n_ports();
2873                         } else {
2874                                 ProcessorList::iterator before = loc;
2875                                 --before;
2876                                 m_in = (*before)->output_streams ();
2877                         }
2878                         
2879                         _meter->reflect_inputs (m_in);
2880                         
2881                         _processors.insert (loc, _meter);
2882                         
2883                         /* we do not need to reconfigure the processors, because the meter
2884                            (a) is always ready to handle processor_max_streams
2885                            (b) is always an N-in/N-out processor, and thus moving
2886                            it doesn't require any changes to the other processors.
2887                         */
2888                         
2889                         _meter->set_display_to_user (false);
2890                         
2891                 } else {
2892                         
2893                         // just make it visible and let the user move it
2894                         
2895                         _meter->set_display_to_user (true);
2896                 }
2897         }
2898
2899         _meter_point = p;
2900         meter_change (); /* EMIT SIGNAL */
2901
2902         bool const meter_visibly_changed = (_meter->display_to_user() != meter_was_visible_to_user);
2903         
2904         processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, meter_visibly_changed)); /* EMIT SIGNAL */
2905 }
2906
2907 void
2908 Route::put_monitor_send_at (Placement p)
2909 {
2910         if (!_monitor_send) {
2911                 return;
2912         }
2913
2914         {
2915                 Glib::RWLock::WriterLock lm (_processor_lock);
2916                 ProcessorList as_it_was (_processors);
2917                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), _monitor_send);
2918                 _processors.erase(loc);
2919                 
2920                 switch (p) {
2921                 case PreFader:
2922                         loc = find(_processors.begin(), _processors.end(), _amp);
2923                         if (loc != _processors.begin()) {
2924                                 --loc;
2925                         }
2926                         break;
2927                 case PostFader:
2928                         loc = _processors.end();
2929                         break;
2930                 }
2931                 
2932                 _processors.insert (loc, _monitor_send);
2933
2934                 if (configure_processors_unlocked (0)) {
2935                         _processors = as_it_was;
2936                         configure_processors_unlocked (0); // it worked before we tried to add it ...
2937                         return;
2938                 }
2939         }
2940
2941         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2942         _session.set_dirty ();
2943 }
2944
2945 nframes_t
2946 Route::update_total_latency ()
2947 {
2948         nframes_t old = _output->effective_latency();
2949         nframes_t own_latency = _output->user_latency();
2950
2951         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2952                 if ((*i)->active ()) {
2953                         own_latency += (*i)->signal_latency ();
2954                 }
2955         }
2956
2957         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: internal redirect latency = %2\n", _name, own_latency));
2958
2959         _output->set_port_latency (own_latency);
2960
2961         if (_output->user_latency() == 0) {
2962
2963                 /* this (virtual) function is used for pure Routes,
2964                    not derived classes like AudioTrack.  this means
2965                    that the data processed here comes from an input
2966                    port, not prerecorded material, and therefore we
2967                    have to take into account any input latency.
2968                 */
2969
2970                 own_latency += _input->signal_latency ();
2971         }
2972
2973         if (old != own_latency) {
2974                 _output->set_latency_delay (own_latency);
2975                 signal_latency_changed (); /* EMIT SIGNAL */
2976         }
2977
2978         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: input latency = %2 total = %3\n", _name, _input->signal_latency(), own_latency));
2979
2980         return _output->effective_latency ();
2981 }
2982
2983 void
2984 Route::set_user_latency (nframes_t nframes)
2985 {
2986         _output->set_user_latency (nframes);
2987         _session.update_latency_compensation (false, false);
2988 }
2989
2990 void
2991 Route::set_latency_delay (nframes_t longest_session_latency)
2992 {
2993         nframes_t old = _initial_delay;
2994
2995         if (_output->effective_latency() < longest_session_latency) {
2996                 _initial_delay = longest_session_latency - _output->effective_latency();
2997         } else {
2998                 _initial_delay = 0;
2999         }
3000
3001         if (_initial_delay != old) {
3002                 initial_delay_changed (); /* EMIT SIGNAL */
3003         }
3004
3005         if (_session.transport_stopped()) {
3006                 _roll_delay = _initial_delay;
3007         }
3008 }
3009
3010 void
3011 Route::automation_snapshot (nframes_t now, bool force)
3012 {
3013         panner()->automation_snapshot (now, force);
3014         
3015         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3016                 (*i)->automation_snapshot (now, force);
3017         }
3018 }
3019
3020 Route::SoloControllable::SoloControllable (std::string name, Route& r)
3021         : AutomationControl (r.session(), Evoral::Parameter (SoloAutomation),
3022                              boost::shared_ptr<AutomationList>(), name)
3023         , route (r)
3024 {
3025         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(SoloAutomation)));
3026         set_list (gl);
3027 }
3028
3029 void
3030 Route::SoloControllable::set_value (double val)
3031 {
3032         bool bval = ((val >= 0.5f) ? true: false);
3033 # if 0
3034         this is how it should be done 
3035
3036         boost::shared_ptr<RouteList> rl (new RouteList);
3037         rl->push_back (route);
3038
3039         if (Config->get_solo_control_is_listen_control()) {
3040                 _session.set_listen (rl, bval);
3041         } else {
3042                 _session.set_solo (rl, bval);
3043         }
3044 #else
3045         route.set_solo (bval, this);
3046 #endif
3047 }
3048
3049 double
3050 Route::SoloControllable::get_value (void) const
3051 {
3052         if (Config->get_solo_control_is_listen_control()) {
3053                 return route.listening() ? 1.0f : 0.0f;
3054         } else {
3055                 return route.self_soloed() ? 1.0f : 0.0f;
3056         }
3057 }
3058
3059 Route::MuteControllable::MuteControllable (std::string name, Route& r)
3060         : AutomationControl (r.session(), Evoral::Parameter (MuteAutomation),
3061                              boost::shared_ptr<AutomationList>(), name)
3062         , route (r)
3063 {
3064         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(MuteAutomation)));
3065         set_list (gl);
3066 }
3067
3068 void
3069 Route::MuteControllable::set_value (double val)
3070 {
3071         bool bval = ((val >= 0.5f) ? true: false);
3072 # if 0
3073         this is how it should be done 
3074
3075         boost::shared_ptr<RouteList> rl (new RouteList);
3076         rl->push_back (route);
3077         _session.set_mute (rl, bval);
3078 #else
3079         route.set_mute (bval, this);
3080 #endif
3081 }
3082
3083 double
3084 Route::MuteControllable::get_value (void) const
3085 {
3086         return route.muted() ? 1.0f : 0.0f;
3087 }
3088
3089 void
3090 Route::set_block_size (nframes_t nframes)
3091 {
3092         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3093                 (*i)->set_block_size (nframes);
3094         }
3095         
3096         _session.ensure_buffers (n_process_buffers ());
3097 }
3098
3099 void
3100 Route::protect_automation ()
3101 {
3102         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
3103                 (*i)->protect_automation();
3104 }
3105
3106 void
3107 Route::set_pending_declick (int declick)
3108 {
3109         if (_declickable) {
3110                 /* this call is not allowed to turn off a pending declick unless "force" is true */
3111                 if (declick) {
3112                         _pending_declick = declick;
3113                 }
3114                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
3115         } else {
3116                 _pending_declick = 0;
3117         }
3118
3119 }
3120
3121 /** Shift automation forwards from a particular place, thereby inserting time.
3122  *  Adds undo commands for any shifts that are performed.
3123  *
3124  * @param pos Position to start shifting from.
3125  * @param frames Amount to shift forwards by.
3126  */
3127
3128 void
3129 Route::shift (nframes64_t /*pos*/, nframes64_t /*frames*/)
3130 {
3131 #ifdef THIS_NEEDS_FIXING_FOR_V3
3132
3133         /* gain automation */
3134         XMLNode &before = _gain_control->get_state ();
3135         _gain_control->shift (pos, frames);
3136         XMLNode &after = _gain_control->get_state ();
3137         _session.add_command (new MementoCommand<AutomationList> (_gain_automation_curve, &before, &after));
3138
3139         /* pan automation */
3140         for (std::vector<StreamPanner*>::iterator i = _panner->begin (); i != _panner->end (); ++i) {
3141                 Curve & c = (*i)->automation ();
3142                 XMLNode &before = c.get_state ();
3143                 c.shift (pos, frames);
3144                 XMLNode &after = c.get_state ();
3145                 _session.add_command (new MementoCommand<AutomationList> (c, &before, &after));
3146         }
3147
3148         /* redirect automation */
3149         {
3150                 Glib::RWLock::ReaderLock lm (redirect_lock);
3151                 for (RedirectList::iterator i = _redirects.begin (); i != _redirects.end (); ++i) {
3152
3153                         set<uint32_t> a;
3154                         (*i)->what_has_automation (a);
3155
3156                         for (set<uint32_t>::const_iterator j = a.begin (); j != a.end (); ++j) {
3157                                 AutomationList & al = (*i)->automation_list (*j);
3158                                 XMLNode &before = al.get_state ();
3159                                 al.shift (pos, frames);
3160                                 XMLNode &after = al.get_state ();
3161                                 _session.add_command (new MementoCommand<AutomationList> (al, &before, &after));
3162                         }
3163                 }
3164         }
3165 #endif
3166
3167 }
3168
3169
3170 int
3171 Route::save_as_template (const string& path, const string& name)
3172 {
3173         XMLNode& node (state (false));
3174         XMLTree tree;
3175
3176         IO::set_name_in_state (*node.children().front(), name);
3177
3178         tree.set_root (&node);
3179         return tree.write (path.c_str());
3180 }
3181
3182
3183 bool
3184 Route::set_name (const string& str)
3185 {
3186         bool ret;
3187         string ioproc_name;
3188         string name;
3189
3190         name = Route::ensure_track_or_route_name (str, _session);
3191         SessionObject::set_name (name);
3192
3193         ret = (_input->set_name(name) && _output->set_name(name));
3194
3195         if (ret) {
3196
3197                 Glib::RWLock::ReaderLock lm (_processor_lock);
3198
3199                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3200
3201                         /* rename all I/O processors that have inputs or outputs */
3202
3203                         boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor> (*i);
3204
3205                         if (iop && (iop->output() || iop->input())) {
3206                                 if (!iop->set_name (name)) {
3207                                         ret = false;
3208                                 }
3209                         }
3210                 }
3211
3212         }
3213
3214         return ret;
3215 }
3216
3217 boost::shared_ptr<Send>
3218 Route::internal_send_for (boost::shared_ptr<const Route> target) const
3219 {
3220         Glib::RWLock::ReaderLock lm (_processor_lock);
3221
3222         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3223                 boost::shared_ptr<InternalSend> send;
3224
3225                 if ((send = boost::dynamic_pointer_cast<InternalSend>(*i)) != 0) {
3226                         if (send->target_route() == target) {
3227                                 return send;
3228                         }
3229                 }
3230         }
3231
3232         return boost::shared_ptr<Send>();
3233 }
3234
3235 /** @param c Audio channel index.
3236  *  @param yn true to invert phase, otherwise false.
3237  */
3238 void
3239 Route::set_phase_invert (uint32_t c, bool yn)
3240 {
3241         if (_phase_invert[c] != yn) {
3242                 _phase_invert[c] = yn;
3243                 phase_invert_changed (); /* EMIT SIGNAL */
3244                 _session.set_dirty ();
3245         }
3246 }
3247
3248 void
3249 Route::set_phase_invert (boost::dynamic_bitset<> p)
3250 {
3251         if (_phase_invert != p) {
3252                 _phase_invert = p;
3253                 phase_invert_changed (); /* EMIT SIGNAL */
3254                 _session.set_dirty ();
3255         }
3256 }
3257
3258 bool
3259 Route::phase_invert (uint32_t c) const
3260 {
3261         return _phase_invert[c];
3262 }
3263
3264 boost::dynamic_bitset<>
3265 Route::phase_invert () const
3266 {
3267         return _phase_invert;
3268 }
3269
3270 void
3271 Route::set_denormal_protection (bool yn)
3272 {
3273         if (_denormal_protection != yn) {
3274                 _denormal_protection = yn;
3275                 denormal_protection_changed (); /* EMIT SIGNAL */
3276         }
3277 }
3278
3279 bool
3280 Route::denormal_protection () const
3281 {
3282         return _denormal_protection;
3283 }
3284
3285 void
3286 Route::set_active (bool yn)
3287 {
3288         if (_active != yn) {
3289                 _active = yn;
3290                 _input->set_active (yn);
3291                 _output->set_active (yn);
3292                 active_changed (); // EMIT SIGNAL
3293         }
3294 }
3295
3296 void
3297 Route::meter ()
3298 {
3299         Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
3300
3301         assert (_meter);
3302
3303         _meter->meter ();
3304
3305         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3306
3307                 boost::shared_ptr<Send> s;
3308                 boost::shared_ptr<Return> r;
3309
3310                 if ((s = boost::dynamic_pointer_cast<Send> (*i)) != 0) {
3311                         s->meter()->meter();
3312                 } else if ((r = boost::dynamic_pointer_cast<Return> (*i)) != 0) {
3313                         r->meter()->meter ();
3314                 }
3315         }
3316 }
3317
3318 boost::shared_ptr<Panner>
3319 Route::panner() const
3320 {
3321         return _main_outs->panner();
3322 }
3323
3324 boost::shared_ptr<AutomationControl>
3325 Route::gain_control() const
3326 {
3327         return _amp->gain_control();
3328 }
3329
3330 boost::shared_ptr<AutomationControl>
3331 Route::get_control (const Evoral::Parameter& param)
3332 {
3333         /* either we own the control or .... */
3334
3335         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(control (param));
3336
3337         if (!c) {
3338
3339                 /* maybe one of our processors does or ... */
3340
3341                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
3342                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3343                         if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->control (param))) != 0) {
3344                                 break;
3345                         }
3346                 }
3347         }
3348
3349         if (!c) {
3350
3351                 /* nobody does so we'll make a new one */
3352
3353                 c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
3354                 add_control(c);
3355         }
3356
3357         return c;
3358 }
3359
3360 boost::shared_ptr<Processor>
3361 Route::nth_plugin (uint32_t n)
3362 {
3363         Glib::RWLock::ReaderLock lm (_processor_lock);
3364         ProcessorList::iterator i;
3365
3366         for (i = _processors.begin(); i != _processors.end(); ++i) {
3367                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
3368                         if (n-- == 0) {
3369                                 return *i;
3370                         }
3371                 }
3372         }
3373
3374         return boost::shared_ptr<Processor> ();
3375 }
3376
3377 boost::shared_ptr<Processor>
3378 Route::nth_send (uint32_t n)
3379 {
3380         Glib::RWLock::ReaderLock lm (_processor_lock);
3381         ProcessorList::iterator i;
3382
3383         for (i = _processors.begin(); i != _processors.end(); ++i) {
3384                 if (boost::dynamic_pointer_cast<Send> (*i)) {
3385                         if (n-- == 0) {
3386                                 return *i;
3387                         }
3388                 } 
3389         }
3390
3391         return boost::shared_ptr<Processor> ();
3392 }
3393
3394 bool
3395 Route::has_io_processor_named (const string& name)
3396 {
3397         Glib::RWLock::ReaderLock lm (_processor_lock);
3398         ProcessorList::iterator i;
3399         
3400         for (i = _processors.begin(); i != _processors.end(); ++i) {
3401                 if (boost::dynamic_pointer_cast<Send> (*i) ||
3402                     boost::dynamic_pointer_cast<PortInsert> (*i)) {
3403                         if ((*i)->name() == name) {
3404                                 return true;
3405                         }
3406                 }
3407         }
3408         
3409         return false;
3410 }
3411
3412 MuteMaster::MutePoint
3413 Route::mute_points () const
3414 {
3415         return _mute_master->mute_points ();
3416 }
3417
3418 void
3419 Route::set_processor_positions ()
3420 {
3421         Glib::RWLock::ReaderLock lm (_processor_lock);
3422
3423         bool had_amp = false;
3424         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3425                 (*i)->set_pre_fader (!had_amp);
3426                 if (boost::dynamic_pointer_cast<Amp> (*i)) {
3427                         had_amp = true;
3428                 }
3429         }
3430 }
3431