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