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