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