fix two major assert failures arising from the optional monitor section commit; separ...
[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::RWLock::ReaderLock rm (_processor_lock);
2555
2556         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2557                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2558
2559                 if (d) {
2560                         return d->add_send (send);
2561                 }
2562         }
2563 }
2564
2565 void
2566 Route::remove_send_from_internal_return (InternalSend* send)
2567 {
2568         Glib::RWLock::ReaderLock rm (_processor_lock);
2569
2570         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2571                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2572
2573                 if (d) {
2574                         return d->remove_send (send);
2575                 }
2576         }
2577 }
2578
2579 void
2580 Route::enable_monitor_send ()
2581 {
2582         /* Caller must hold process lock */
2583         assert (!AudioEngine::instance()->process_lock().trylock());
2584
2585         /* master never sends to monitor section via the normal mechanism */
2586         assert (!is_master ());
2587
2588         /* make sure we have one */
2589         if (!_monitor_send) {
2590                 _monitor_send.reset (new InternalSend (_session, _pannable, _mute_master, _session.monitor_out(), Delivery::Listen));
2591                 _monitor_send->set_display_to_user (false);
2592         }
2593
2594         /* set it up */
2595         configure_processors (0);
2596 }
2597
2598 /** Add an aux send to a route.
2599  *  @param route route to send to.
2600  *  @param placement placement for the send.
2601  */
2602 int
2603 Route::add_aux_send (boost::shared_ptr<Route> route, Placement placement)
2604 {
2605         assert (route != _session.monitor_out ());
2606
2607         {
2608                 Glib::RWLock::ReaderLock rm (_processor_lock);
2609
2610                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
2611
2612                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend> (*x);
2613
2614                         if (d && d->target_route() == route) {
2615                                 /* already listening via the specified IO: do nothing */
2616                                 return 0;
2617                         }
2618                 }
2619         }
2620
2621         try {
2622
2623                 boost::shared_ptr<InternalSend> listener;
2624
2625                 {
2626                         Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2627                         listener.reset (new InternalSend (_session, _pannable, _mute_master, route, Delivery::Aux));
2628                 }
2629
2630                 add_processor (listener, placement);
2631
2632         } catch (failed_constructor& err) {
2633                 return -1;
2634         }
2635
2636         return 0;
2637 }
2638
2639 void
2640 Route::remove_aux_or_listen (boost::shared_ptr<Route> route)
2641 {
2642         ProcessorStreams err;
2643         ProcessorList::iterator tmp;
2644
2645         {
2646                 Glib::RWLock::ReaderLock rl(_processor_lock);
2647
2648                 /* have to do this early because otherwise processor reconfig
2649                  * will put _monitor_send back in the list
2650                  */
2651
2652                 if (route == _session.monitor_out()) {
2653                         _monitor_send.reset ();
2654                 }
2655
2656           again:
2657                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
2658                         
2659                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
2660                         
2661                         if (d && d->target_route() == route) {
2662                                 rl.release ();
2663                                 remove_processor (*x, &err, false);
2664                                 rl.acquire ();
2665
2666                                 /* list could have been demolished while we dropped the lock
2667                                    so start over.
2668                                 */
2669                                 
2670                                 goto again;
2671                         }
2672                 }
2673         }
2674 }
2675
2676 void
2677 Route::set_comment (string cmt, void *src)
2678 {
2679         _comment = cmt;
2680         comment_changed (src);
2681         _session.set_dirty ();
2682 }
2683
2684 bool
2685 Route::add_fed_by (boost::shared_ptr<Route> other, bool via_sends_only)
2686 {
2687         FeedRecord fr (other, via_sends_only);
2688
2689         pair<FedBy::iterator,bool> result =  _fed_by.insert (fr);
2690
2691         if (!result.second) {
2692
2693                 /* already a record for "other" - make sure sends-only information is correct */
2694                 if (!via_sends_only && result.first->sends_only) {
2695                         FeedRecord* frp = const_cast<FeedRecord*>(&(*result.first));
2696                         frp->sends_only = false;
2697                 }
2698         }
2699
2700         return result.second;
2701 }
2702
2703 void
2704 Route::clear_fed_by ()
2705 {
2706         _fed_by.clear ();
2707 }
2708
2709 bool
2710 Route::feeds (boost::shared_ptr<Route> other, bool* via_sends_only)
2711 {
2712         const FedBy& fed_by (other->fed_by());
2713
2714         for (FedBy::iterator f = fed_by.begin(); f != fed_by.end(); ++f) {
2715                 boost::shared_ptr<Route> sr = f->r.lock();
2716
2717                 if (sr && (sr.get() == this)) {
2718
2719                         if (via_sends_only) {
2720                                 *via_sends_only = f->sends_only;
2721                         }
2722
2723                         return true;
2724                 }
2725         }
2726
2727         return false;
2728 }
2729
2730 bool
2731 Route::direct_feeds_according_to_reality (boost::shared_ptr<Route> other, bool* via_send_only)
2732 {
2733         DEBUG_TRACE (DEBUG::Graph, string_compose ("Feeds? %1\n", _name));
2734
2735         if (_output->connected_to (other->input())) {
2736                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\tdirect FEEDS %2\n", other->name()));
2737                 if (via_send_only) {
2738                         *via_send_only = false;
2739                 }
2740
2741                 return true;
2742         }
2743
2744
2745         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); ++r) {
2746
2747                 boost::shared_ptr<IOProcessor> iop;
2748
2749                 if ((iop = boost::dynamic_pointer_cast<IOProcessor>(*r)) != 0) {
2750                         if (iop->feeds (other)) {
2751                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does feed %2\n", iop->name(), other->name()));
2752                                 if (via_send_only) {
2753                                         *via_send_only = true;
2754                                 }
2755                                 return true;
2756                         } else {
2757                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does NOT feed %2\n", iop->name(), other->name()));
2758                         }
2759                 } else {
2760                         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tPROC %1 is not an IOP\n", (*r)->name()));
2761                 }
2762
2763         }
2764
2765         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tdoes NOT feed %1\n", other->name()));
2766         return false;
2767 }
2768
2769 bool
2770 Route::direct_feeds_according_to_graph (boost::shared_ptr<Route> other, bool* via_send_only)
2771 {
2772         return _session._current_route_graph.has (shared_from_this (), other, via_send_only);
2773 }
2774
2775 /** Called from the (non-realtime) butler thread when the transport is stopped */
2776 void
2777 Route::nonrealtime_handle_transport_stopped (bool /*abort_ignored*/, bool did_locate, bool can_flush_processors)
2778 {
2779         framepos_t now = _session.transport_frame();
2780
2781         {
2782                 Glib::RWLock::ReaderLock lm (_processor_lock);
2783
2784                 if (!did_locate) {
2785                         automation_snapshot (now, true);
2786                 }
2787
2788                 Automatable::transport_stopped (now);
2789
2790                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2791
2792                         if (!_have_internal_generator && (Config->get_plugins_stop_with_transport() && can_flush_processors)) {
2793                                 (*i)->flush ();
2794                         }
2795
2796                         (*i)->transport_stopped (now);
2797                 }
2798         }
2799
2800         _roll_delay = _initial_delay;
2801 }
2802
2803 /** Called with the process lock held if change contains ConfigurationChanged */
2804 void
2805 Route::input_change_handler (IOChange change, void * /*src*/)
2806 {
2807         if ((change.type & IOChange::ConfigurationChanged)) {
2808                 configure_processors (0);
2809                 _phase_invert.resize (_input->n_ports().n_audio ());
2810                 io_changed (); /* EMIT SIGNAL */
2811         }
2812 }
2813
2814 uint32_t
2815 Route::pans_required () const
2816 {
2817         if (n_outputs().n_audio() < 2) {
2818                 return 0;
2819         }
2820
2821         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
2822 }
2823
2824 int
2825 Route::no_roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, bool session_state_changing)
2826 {
2827         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2828         if (!lm.locked()) {
2829                 return 0;
2830         }
2831
2832         if (n_outputs().n_total() == 0) {
2833                 return 0;
2834         }
2835
2836         if (!_active || n_inputs() == ChanCount::ZERO)  {
2837                 silence_unlocked (nframes);
2838                 return 0;
2839         }
2840         if (session_state_changing) {
2841                 if (_session.transport_speed() != 0.0f) {
2842                         /* we're rolling but some state is changing (e.g. our diskstream contents)
2843                            so we cannot use them. Be silent till this is over.
2844
2845                            XXX note the absurdity of ::no_roll() being called when we ARE rolling!
2846                         */
2847                         silence_unlocked (nframes);
2848                         return 0;
2849                 }
2850                 /* we're really not rolling, so we're either delivery silence or actually
2851                    monitoring, both of which are safe to do while session_state_changing is true.
2852                 */
2853         }
2854
2855         _amp->apply_gain_automation (false);
2856         passthru (start_frame, end_frame, nframes, 0);
2857
2858         return 0;
2859 }
2860
2861 int
2862 Route::roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& /* need_butler */)
2863 {
2864         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2865         if (!lm.locked()) {
2866                 return 0;
2867         }
2868
2869         automation_snapshot (_session.transport_frame(), false);
2870
2871         if (n_outputs().n_total() == 0) {
2872                 return 0;
2873         }
2874
2875         if (!_active || n_inputs().n_total() == 0) {
2876                 silence_unlocked (nframes);
2877                 return 0;
2878         }
2879
2880         framecnt_t unused = 0;
2881
2882         if ((nframes = check_initial_delay (nframes, unused)) == 0) {
2883                 return 0;
2884         }
2885
2886         _silent = false;
2887
2888         passthru (start_frame, end_frame, nframes, declick);
2889
2890         return 0;
2891 }
2892
2893 int
2894 Route::silent_roll (pframes_t nframes, framepos_t /*start_frame*/, framepos_t /*end_frame*/, bool& /* need_butler */)
2895 {
2896         silence (nframes);
2897         return 0;
2898 }
2899
2900 bool
2901 Route::has_external_redirects () const
2902 {
2903         // FIXME: what about sends? - they don't return a signal back to ardour?
2904
2905         boost::shared_ptr<const PortInsert> pi;
2906
2907         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2908
2909                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2910
2911                         for (PortSet::const_iterator port = pi->output()->ports().begin(); port != pi->output()->ports().end(); ++port) {
2912
2913                                 string port_name = port->name();
2914                                 string client_name = port_name.substr (0, port_name.find(':'));
2915
2916                                 /* only say "yes" if the redirect is actually in use */
2917
2918                                 if (client_name != "ardour" && pi->active()) {
2919                                         return true;
2920                                 }
2921                         }
2922                 }
2923         }
2924
2925         return false;
2926 }
2927
2928 void
2929 Route::flush_processors ()
2930 {
2931         /* XXX shouldn't really try to take this lock, since
2932            this is called from the RT audio thread.
2933         */
2934
2935         Glib::RWLock::ReaderLock lm (_processor_lock);
2936
2937         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2938                 (*i)->flush ();
2939         }
2940 }
2941
2942 void
2943 Route::set_meter_point (MeterPoint p, bool force)
2944 {
2945         /* CAN BE CALLED FROM PROCESS CONTEXT */
2946
2947         if (_meter_point == p && !force) {
2948                 return;
2949         }
2950
2951         bool meter_was_visible_to_user = _meter->display_to_user ();
2952
2953         {
2954                 Glib::RWLock::WriterLock lm (_processor_lock);
2955
2956                 maybe_note_meter_position ();
2957
2958                 _meter_point = p;
2959
2960                 if (_meter_point != MeterCustom) {
2961
2962                         _meter->set_display_to_user (false);
2963
2964                         setup_invisible_processors ();
2965
2966                 } else {
2967
2968                         _meter->set_display_to_user (true);
2969
2970                         /* If we have a previous position for the custom meter, try to put it there */
2971                         if (_custom_meter_position_noted) {
2972                                 boost::shared_ptr<Processor> after = _processor_after_last_custom_meter.lock ();
2973                                 
2974                                 if (after) {
2975                                         ProcessorList::iterator i = find (_processors.begin(), _processors.end(), after);
2976                                         if (i != _processors.end ()) {
2977                                                 _processors.remove (_meter);
2978                                                 _processors.insert (i, _meter);
2979                                         }
2980                                 } else if (_last_custom_meter_was_at_end) {
2981                                         _processors.remove (_meter);
2982                                         _processors.push_back (_meter);
2983                                 }
2984                         }
2985                 }
2986
2987                 /* Set up the meter for its new position */
2988
2989                 ProcessorList::iterator loc = find (_processors.begin(), _processors.end(), _meter);
2990                 
2991                 ChanCount m_in;
2992                 
2993                 if (loc == _processors.begin()) {
2994                         m_in = _input->n_ports();
2995                 } else {
2996                         ProcessorList::iterator before = loc;
2997                         --before;
2998                         m_in = (*before)->output_streams ();
2999                 }
3000                 
3001                 _meter->reflect_inputs (m_in);
3002                 
3003                 /* we do not need to reconfigure the processors, because the meter
3004                    (a) is always ready to handle processor_max_streams
3005                    (b) is always an N-in/N-out processor, and thus moving
3006                    it doesn't require any changes to the other processors.
3007                 */
3008         }
3009
3010         meter_change (); /* EMIT SIGNAL */
3011
3012         bool const meter_visibly_changed = (_meter->display_to_user() != meter_was_visible_to_user);
3013
3014         processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, meter_visibly_changed)); /* EMIT SIGNAL */
3015 }
3016
3017 void
3018 Route::listen_position_changed ()
3019 {
3020         {
3021                 Glib::RWLock::WriterLock lm (_processor_lock);
3022                 ProcessorState pstate (this);
3023
3024                 {
3025                         Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3026
3027                         if (configure_processors_unlocked (0)) {
3028                                 pstate.restore ();
3029                                 configure_processors_unlocked (0); // it worked before we tried to add it ...
3030                                 return;
3031                         }
3032                 }
3033         }
3034
3035         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
3036         _session.set_dirty ();
3037 }
3038
3039 boost::shared_ptr<CapturingProcessor>
3040 Route::add_export_point()
3041 {
3042         if (!_capturing_processor) {
3043
3044                 _capturing_processor.reset (new CapturingProcessor (_session));
3045                 _capturing_processor->activate ();
3046
3047                 {
3048                         Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3049                         configure_processors (0);
3050                 }
3051
3052         }
3053
3054         return _capturing_processor;
3055 }
3056
3057 framecnt_t
3058 Route::update_signal_latency ()
3059 {
3060         framecnt_t l = _output->user_latency();
3061
3062         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3063                 if ((*i)->active ()) {
3064                         l += (*i)->signal_latency ();
3065                 }
3066         }
3067
3068         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: internal signal latency = %2\n", _name, l));
3069
3070         if (_signal_latency != l) {
3071                 _signal_latency = l;
3072                 signal_latency_changed (); /* EMIT SIGNAL */
3073         }
3074
3075         return _signal_latency;
3076 }
3077
3078 void
3079 Route::set_user_latency (framecnt_t nframes)
3080 {
3081         _output->set_user_latency (nframes);
3082         _session.update_latency_compensation ();
3083 }
3084
3085 void
3086 Route::set_latency_compensation (framecnt_t longest_session_latency)
3087 {
3088         framecnt_t old = _initial_delay;
3089
3090         if (_signal_latency < longest_session_latency) {
3091                 _initial_delay = longest_session_latency - _signal_latency;
3092         } else {
3093                 _initial_delay = 0;
3094         }
3095
3096         DEBUG_TRACE (DEBUG::Latency, string_compose (
3097                              "%1: compensate for maximum latency of %2,"
3098                              "given own latency of %3, using initial delay of %4\n",
3099                              name(), longest_session_latency, _signal_latency, _initial_delay));
3100
3101         if (_initial_delay != old) {
3102                 initial_delay_changed (); /* EMIT SIGNAL */
3103         }
3104
3105         if (_session.transport_stopped()) {
3106                 _roll_delay = _initial_delay;
3107         }
3108 }
3109
3110 void
3111 Route::automation_snapshot (framepos_t now, bool force)
3112 {
3113         if (_pannable) {
3114                 _pannable->automation_snapshot (now, force);
3115         }
3116
3117         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3118                 (*i)->automation_snapshot (now, force);
3119         }
3120 }
3121
3122 Route::SoloControllable::SoloControllable (std::string name, boost::shared_ptr<Route> r)
3123         : AutomationControl (r->session(), Evoral::Parameter (SoloAutomation),
3124                              boost::shared_ptr<AutomationList>(), name)
3125         , _route (r)
3126 {
3127         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(SoloAutomation)));
3128         set_list (gl);
3129 }
3130
3131 void
3132 Route::SoloControllable::set_value (double val)
3133 {
3134         bool bval = ((val >= 0.5f) ? true: false);
3135
3136         boost::shared_ptr<RouteList> rl (new RouteList);
3137
3138         boost::shared_ptr<Route> r = _route.lock ();
3139         if (!r) {
3140                 return;
3141         }
3142
3143         rl->push_back (r);
3144
3145         if (Config->get_solo_control_is_listen_control()) {
3146                 _session.set_listen (rl, bval);
3147         } else {
3148                 _session.set_solo (rl, bval);
3149         }
3150 }
3151
3152 double
3153 Route::SoloControllable::get_value () const
3154 {
3155         boost::shared_ptr<Route> r = _route.lock ();
3156         if (!r) {
3157                 return 0;
3158         }
3159
3160         if (Config->get_solo_control_is_listen_control()) {
3161                 return r->listening_via_monitor() ? 1.0f : 0.0f;
3162         } else {
3163                 return r->self_soloed() ? 1.0f : 0.0f;
3164         }
3165 }
3166
3167 Route::MuteControllable::MuteControllable (std::string name, boost::shared_ptr<Route> r)
3168         : AutomationControl (r->session(), Evoral::Parameter (MuteAutomation),
3169                              boost::shared_ptr<AutomationList>(), name)
3170         , _route (r)
3171 {
3172         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(MuteAutomation)));
3173         set_list (gl);
3174 }
3175
3176 void
3177 Route::MuteControllable::set_value (double val)
3178 {
3179         bool bval = ((val >= 0.5f) ? true: false);
3180
3181         boost::shared_ptr<RouteList> rl (new RouteList);
3182
3183         boost::shared_ptr<Route> r = _route.lock ();
3184         if (!r) {
3185                 return;
3186         }
3187
3188         rl->push_back (r);
3189         _session.set_mute (rl, bval);
3190 }
3191
3192 double
3193 Route::MuteControllable::get_value () const
3194 {
3195         boost::shared_ptr<Route> r = _route.lock ();
3196         if (!r) {
3197                 return 0;
3198         }
3199
3200         return r->muted() ? 1.0f : 0.0f;
3201 }
3202
3203 void
3204 Route::set_block_size (pframes_t nframes)
3205 {
3206         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3207                 (*i)->set_block_size (nframes);
3208         }
3209
3210         _session.ensure_buffers (n_process_buffers ());
3211 }
3212
3213 void
3214 Route::protect_automation ()
3215 {
3216         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
3217                 (*i)->protect_automation();
3218 }
3219
3220 void
3221 Route::set_pending_declick (int declick)
3222 {
3223         if (_declickable) {
3224                 /* this call is not allowed to turn off a pending declick unless "force" is true */
3225                 if (declick) {
3226                         _pending_declick = declick;
3227                 }
3228                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
3229         } else {
3230                 _pending_declick = 0;
3231         }
3232
3233 }
3234
3235 /** Shift automation forwards from a particular place, thereby inserting time.
3236  *  Adds undo commands for any shifts that are performed.
3237  *
3238  * @param pos Position to start shifting from.
3239  * @param frames Amount to shift forwards by.
3240  */
3241
3242 void
3243 Route::shift (framepos_t pos, framecnt_t frames)
3244 {
3245         /* gain automation */
3246         {
3247                 boost::shared_ptr<AutomationControl> gc = _amp->gain_control();
3248
3249                 XMLNode &before = gc->alist()->get_state ();
3250                 gc->alist()->shift (pos, frames);
3251                 XMLNode &after = gc->alist()->get_state ();
3252                 _session.add_command (new MementoCommand<AutomationList> (*gc->alist().get(), &before, &after));
3253         }
3254
3255         /* pan automation */
3256         if (_pannable) {
3257                 ControlSet::Controls& c (_pannable->controls());
3258
3259                 for (ControlSet::Controls::const_iterator ci = c.begin(); ci != c.end(); ++ci) {
3260                         boost::shared_ptr<AutomationControl> pc = boost::dynamic_pointer_cast<AutomationControl> (ci->second);
3261                         if (pc) {
3262                                 boost::shared_ptr<AutomationList> al = pc->alist();
3263                                 XMLNode& before = al->get_state ();
3264                                 al->shift (pos, frames);
3265                                 XMLNode& after = al->get_state ();
3266                                 _session.add_command (new MementoCommand<AutomationList> (*al.get(), &before, &after));
3267                         }
3268                 }
3269         }
3270
3271         /* redirect automation */
3272         {
3273                 Glib::RWLock::ReaderLock lm (_processor_lock);
3274                 for (ProcessorList::iterator i = _processors.begin (); i != _processors.end (); ++i) {
3275
3276                         set<Evoral::Parameter> parameters = (*i)->what_can_be_automated();
3277
3278                         for (set<Evoral::Parameter>::const_iterator p = parameters.begin (); p != parameters.end (); ++p) {
3279                                 boost::shared_ptr<AutomationControl> ac = (*i)->automation_control (*p);
3280                                 if (ac) {
3281                                         boost::shared_ptr<AutomationList> al = ac->alist();
3282                                         XMLNode &before = al->get_state ();
3283                                         al->shift (pos, frames);
3284                                         XMLNode &after = al->get_state ();
3285                                         _session.add_command (new MementoCommand<AutomationList> (*al.get(), &before, &after));
3286                                 }
3287                         }
3288                 }
3289         }
3290 }
3291
3292
3293 int
3294 Route::save_as_template (const string& path, const string& name)
3295 {
3296         XMLNode& node (state (false));
3297         XMLTree tree;
3298
3299         IO::set_name_in_state (*node.children().front(), name);
3300
3301         tree.set_root (&node);
3302         return tree.write (path.c_str());
3303 }
3304
3305
3306 bool
3307 Route::set_name (const string& str)
3308 {
3309         bool ret;
3310         string ioproc_name;
3311         string name;
3312
3313         name = Route::ensure_track_or_route_name (str, _session);
3314         SessionObject::set_name (name);
3315
3316         ret = (_input->set_name(name) && _output->set_name(name));
3317
3318         if (ret) {
3319                 /* rename the main outs. Leave other IO processors
3320                  * with whatever name they already have, because its
3321                  * just fine as it is (it will not contain the route
3322                  * name if its a port insert, port send or port return).
3323                  */
3324
3325                 if (_main_outs) {
3326                         if (_main_outs->set_name (name)) {
3327                                 /* XXX returning false here is stupid because
3328                                    we already changed the route name.
3329                                 */
3330                                 return false;
3331                         }
3332                 }
3333         }
3334
3335         return ret;
3336 }
3337
3338 /** Set the name of a route in an XML description.
3339  *  @param node XML <Route> node to set the name in.
3340  *  @param name New name.
3341  */
3342 void
3343 Route::set_name_in_state (XMLNode& node, string const & name)
3344 {
3345         node.add_property (X_("name"), name);
3346
3347         XMLNodeList children = node.children();
3348         for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
3349                 
3350                 if ((*i)->name() == X_("IO")) {
3351
3352                         IO::set_name_in_state (**i, name);
3353
3354                 } else if ((*i)->name() == X_("Processor")) {
3355
3356                         XMLProperty* role = (*i)->property (X_("role"));
3357                         if (role && role->value() == X_("Main")) {
3358                                 (*i)->add_property (X_("name"), name);
3359                         }
3360                         
3361                 } else if ((*i)->name() == X_("Diskstream")) {
3362
3363                         (*i)->add_property (X_("playlist"), string_compose ("%1.1", name).c_str());
3364                         (*i)->add_property (X_("name"), name);
3365                         
3366                 }
3367         }
3368 }
3369
3370 boost::shared_ptr<Send>
3371 Route::internal_send_for (boost::shared_ptr<const Route> target) const
3372 {
3373         Glib::RWLock::ReaderLock lm (_processor_lock);
3374
3375         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3376                 boost::shared_ptr<InternalSend> send;
3377
3378                 if ((send = boost::dynamic_pointer_cast<InternalSend>(*i)) != 0) {
3379                         if (send->target_route() == target) {
3380                                 return send;
3381                         }
3382                 }
3383         }
3384
3385         return boost::shared_ptr<Send>();
3386 }
3387
3388 /** @param c Audio channel index.
3389  *  @param yn true to invert phase, otherwise false.
3390  */
3391 void
3392 Route::set_phase_invert (uint32_t c, bool yn)
3393 {
3394         if (_phase_invert[c] != yn) {
3395                 _phase_invert[c] = yn;
3396                 phase_invert_changed (); /* EMIT SIGNAL */
3397                 _session.set_dirty ();
3398         }
3399 }
3400
3401 void
3402 Route::set_phase_invert (boost::dynamic_bitset<> p)
3403 {
3404         if (_phase_invert != p) {
3405                 _phase_invert = p;
3406                 phase_invert_changed (); /* EMIT SIGNAL */
3407                 _session.set_dirty ();
3408         }
3409 }
3410
3411 bool
3412 Route::phase_invert (uint32_t c) const
3413 {
3414         return _phase_invert[c];
3415 }
3416
3417 boost::dynamic_bitset<>
3418 Route::phase_invert () const
3419 {
3420         return _phase_invert;
3421 }
3422
3423 void
3424 Route::set_denormal_protection (bool yn)
3425 {
3426         if (_denormal_protection != yn) {
3427                 _denormal_protection = yn;
3428                 denormal_protection_changed (); /* EMIT SIGNAL */
3429         }
3430 }
3431
3432 bool
3433 Route::denormal_protection () const
3434 {
3435         return _denormal_protection;
3436 }
3437
3438 void
3439 Route::set_active (bool yn, void* src)
3440 {
3441         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_route_active()) {
3442                 _route_group->foreach_route (boost::bind (&Route::set_active, _1, yn, _route_group));
3443                 return;
3444         }
3445
3446         if (_active != yn) {
3447                 _active = yn;
3448                 _input->set_active (yn);
3449                 _output->set_active (yn);
3450                 active_changed (); // EMIT SIGNAL
3451         }
3452 }
3453
3454 void
3455 Route::meter ()
3456 {
3457         Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
3458
3459         assert (_meter);
3460
3461         _meter->meter ();
3462
3463         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3464
3465                 boost::shared_ptr<Send> s;
3466                 boost::shared_ptr<Return> r;
3467
3468                 if ((s = boost::dynamic_pointer_cast<Send> (*i)) != 0) {
3469                         s->meter()->meter();
3470                 } else if ((r = boost::dynamic_pointer_cast<Return> (*i)) != 0) {
3471                         r->meter()->meter ();
3472                 }
3473         }
3474 }
3475
3476 boost::shared_ptr<Pannable>
3477 Route::pannable() const
3478 {
3479         return _pannable;
3480 }
3481
3482 boost::shared_ptr<Panner>
3483 Route::panner() const
3484 {
3485         /* may be null ! */
3486         return _main_outs->panner_shell()->panner();
3487 }
3488
3489 boost::shared_ptr<PannerShell>
3490 Route::panner_shell() const
3491 {
3492         return _main_outs->panner_shell();
3493 }
3494
3495 boost::shared_ptr<AutomationControl>
3496 Route::gain_control() const
3497 {
3498         return _amp->gain_control();
3499 }
3500
3501 boost::shared_ptr<AutomationControl>
3502 Route::get_control (const Evoral::Parameter& param)
3503 {
3504         /* either we own the control or .... */
3505
3506         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(control (param));
3507
3508         if (!c) {
3509
3510                 /* maybe one of our processors does or ... */
3511
3512                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
3513                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3514                         if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->control (param))) != 0) {
3515                                 break;
3516                         }
3517                 }
3518         }
3519
3520         if (!c) {
3521
3522                 /* nobody does so we'll make a new one */
3523
3524                 c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
3525                 add_control(c);
3526         }
3527
3528         return c;
3529 }
3530
3531 boost::shared_ptr<Processor>
3532 Route::nth_plugin (uint32_t n)
3533 {
3534         Glib::RWLock::ReaderLock lm (_processor_lock);
3535         ProcessorList::iterator i;
3536
3537         for (i = _processors.begin(); i != _processors.end(); ++i) {
3538                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
3539                         if (n-- == 0) {
3540                                 return *i;
3541                         }
3542                 }
3543         }
3544
3545         return boost::shared_ptr<Processor> ();
3546 }
3547
3548 boost::shared_ptr<Processor>
3549 Route::nth_send (uint32_t n)
3550 {
3551         Glib::RWLock::ReaderLock lm (_processor_lock);
3552         ProcessorList::iterator i;
3553
3554         for (i = _processors.begin(); i != _processors.end(); ++i) {
3555                 if (boost::dynamic_pointer_cast<Send> (*i)) {
3556                         if (n-- == 0) {
3557                                 return *i;
3558                         }
3559                 }
3560         }
3561
3562         return boost::shared_ptr<Processor> ();
3563 }
3564
3565 bool
3566 Route::has_io_processor_named (const string& name)
3567 {
3568         Glib::RWLock::ReaderLock lm (_processor_lock);
3569         ProcessorList::iterator i;
3570
3571         for (i = _processors.begin(); i != _processors.end(); ++i) {
3572                 if (boost::dynamic_pointer_cast<Send> (*i) ||
3573                     boost::dynamic_pointer_cast<PortInsert> (*i)) {
3574                         if ((*i)->name() == name) {
3575                                 return true;
3576                         }
3577                 }
3578         }
3579
3580         return false;
3581 }
3582
3583 MuteMaster::MutePoint
3584 Route::mute_points () const
3585 {
3586         return _mute_master->mute_points ();
3587 }
3588
3589 void
3590 Route::set_processor_positions ()
3591 {
3592         Glib::RWLock::ReaderLock lm (_processor_lock);
3593
3594         bool had_amp = false;
3595         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3596                 (*i)->set_pre_fader (!had_amp);
3597                 if (boost::dynamic_pointer_cast<Amp> (*i)) {
3598                         had_amp = true;
3599                 }
3600         }
3601 }
3602
3603 /** Called when there is a proposed change to the input port count */
3604 bool
3605 Route::input_port_count_changing (ChanCount to)
3606 {
3607         list<pair<ChanCount, ChanCount> > c = try_configure_processors (to, 0);
3608         if (c.empty()) {
3609                 /* The processors cannot be configured with the new input arrangement, so
3610                    block the change.
3611                 */
3612                 return true;
3613         }
3614
3615         /* The change is ok */
3616         return false;
3617 }
3618
3619 list<string>
3620 Route::unknown_processors () const
3621 {
3622         list<string> p;
3623
3624         Glib::RWLock::ReaderLock lm (_processor_lock);
3625         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3626                 if (boost::dynamic_pointer_cast<UnknownProcessor const> (*i)) {
3627                         p.push_back ((*i)->name ());
3628                 }
3629         }
3630
3631         return p;
3632 }
3633
3634
3635 framecnt_t
3636 Route::update_port_latencies (PortSet& from, PortSet& to, bool playback, framecnt_t our_latency) const
3637 {
3638         /* we assume that all our input ports feed all our output ports. its not
3639            universally true, but the alternative is way too corner-case to worry about.
3640         */
3641
3642         jack_latency_range_t all_connections;
3643
3644         if (from.empty()) {
3645                 all_connections.min = 0;
3646                 all_connections.max = 0;
3647         } else {
3648                 all_connections.min = ~((jack_nframes_t) 0);
3649                 all_connections.max = 0;
3650                 
3651                 /* iterate over all "from" ports and determine the latency range for all of their
3652                    connections to the "outside" (outside of this Route).
3653                 */
3654                 
3655                 for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
3656                         
3657                         jack_latency_range_t range;
3658                         
3659                         p->get_connected_latency_range (range, playback);
3660                         
3661                         all_connections.min = min (all_connections.min, range.min);
3662                         all_connections.max = max (all_connections.max, range.max);
3663                 }
3664         }
3665
3666         /* set the "from" port latencies to the max/min range of all their connections */
3667
3668         for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
3669                 p->set_private_latency_range (all_connections, playback);
3670         }
3671
3672         /* set the ports "in the direction of the flow" to the same value as above plus our own signal latency */
3673
3674         all_connections.min += our_latency;
3675         all_connections.max += our_latency;
3676
3677         for (PortSet::iterator p = to.begin(); p != to.end(); ++p) {
3678                 p->set_private_latency_range (all_connections, playback);
3679         }
3680
3681         return all_connections.max;
3682 }
3683
3684 framecnt_t
3685 Route::set_private_port_latencies (bool playback) const
3686 {
3687         framecnt_t own_latency = 0;
3688
3689         /* Processor list not protected by lock: MUST BE CALLED FROM PROCESS THREAD
3690            OR LATENCY CALLBACK.
3691
3692            This is called (early) from the latency callback. It computes the REAL
3693            latency associated with each port and stores the result as the "private"
3694            latency of the port. A later call to Route::set_public_port_latencies()
3695            sets all ports to the same value to reflect the fact that we do latency
3696            compensation and so all signals are delayed by the same amount as they
3697            flow through ardour.
3698         */
3699
3700         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3701                 if ((*i)->active ()) {
3702                         own_latency += (*i)->signal_latency ();
3703                 }
3704         }
3705
3706         if (playback) {
3707                 /* playback: propagate latency from "outside the route" to outputs to inputs */
3708                 return update_port_latencies (_output->ports (), _input->ports (), true, own_latency);
3709         } else {
3710                 /* capture: propagate latency from "outside the route" to inputs to outputs */
3711                 return update_port_latencies (_input->ports (), _output->ports (), false, own_latency);
3712         }
3713 }
3714
3715 void
3716 Route::set_public_port_latencies (framecnt_t value, bool playback) const
3717 {
3718         /* this is called to set the JACK-visible port latencies, which take
3719            latency compensation into account.
3720         */
3721
3722         jack_latency_range_t range;
3723
3724         range.min = value;
3725         range.max = value;
3726
3727         {
3728                 const PortSet& ports (_input->ports());
3729                 for (PortSet::const_iterator p = ports.begin(); p != ports.end(); ++p) {
3730                         p->set_public_latency_range (range, playback);
3731                 }
3732         }
3733
3734         {
3735                 const PortSet& ports (_output->ports());
3736                 for (PortSet::const_iterator p = ports.begin(); p != ports.end(); ++p) {
3737                         p->set_public_latency_range (range, playback);
3738                 }
3739         }
3740 }
3741
3742 /** Put the invisible processors in the right place in _processors.
3743  *  Must be called with a writer lock on _processor_lock held.
3744  */
3745 void
3746 Route::setup_invisible_processors ()
3747 {
3748 #ifndef NDEBUG
3749         Glib::RWLock::WriterLock lm (_processor_lock, Glib::TRY_LOCK);
3750         assert (!lm.locked ());
3751 #endif
3752
3753         if (!_main_outs) {
3754                 /* too early to be doing this stuff */
3755                 return;
3756         }
3757
3758         /* we'll build this new list here and then use it */
3759
3760         ProcessorList new_processors;
3761
3762         /* find visible processors */
3763
3764         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3765                 if ((*i)->display_to_user ()) {
3766                         new_processors.push_back (*i);
3767                 }
3768         }
3769
3770         /* find the amp */
3771
3772         ProcessorList::iterator amp = new_processors.begin ();
3773         while (amp != new_processors.end() && boost::dynamic_pointer_cast<Amp> (*amp) == 0) {
3774                 ++amp;
3775         }
3776
3777         assert (amp != _processors.end ());
3778
3779         /* and the processor after the amp */
3780
3781         ProcessorList::iterator after_amp = amp;
3782         ++after_amp;
3783
3784         /* METER */
3785
3786         if (_meter) {
3787                 switch (_meter_point) {
3788                 case MeterInput:
3789                         assert (!_meter->display_to_user ());
3790                         new_processors.push_front (_meter);
3791                         break;
3792                 case MeterPreFader:
3793                         assert (!_meter->display_to_user ());
3794                         new_processors.insert (amp, _meter);
3795                         break;
3796                 case MeterPostFader:
3797                         /* do nothing here */
3798                         break;
3799                 case MeterOutput:
3800                         /* do nothing here */
3801                         break;
3802                 case MeterCustom:
3803                         /* the meter is visible, so we don't touch it here */
3804                         break;
3805                 }
3806         }
3807
3808         /* MAIN OUTS */
3809
3810         assert (_main_outs);
3811         assert (!_main_outs->display_to_user ());
3812         new_processors.push_back (_main_outs);
3813
3814         /* iterator for the main outs */
3815
3816         ProcessorList::iterator main = new_processors.end();
3817         --main;
3818
3819         /* OUTPUT METERING */
3820
3821         if (_meter && (_meter_point == MeterOutput || _meter_point == MeterPostFader)) {
3822                 assert (!_meter->display_to_user ());
3823
3824                 /* add the processor just before or just after the main outs */
3825
3826                 ProcessorList::iterator meter_point = main;
3827
3828                 if (_meter_point == MeterOutput) {
3829                         ++meter_point;
3830                 }
3831                 new_processors.insert (meter_point, _meter);
3832         }
3833
3834         /* MONITOR SEND */
3835
3836         if (_monitor_send && !is_monitor ()) {
3837                 assert (!_monitor_send->display_to_user ());
3838                 if (Config->get_solo_control_is_listen_control()) {
3839                         switch (Config->get_listen_position ()) {
3840                         case PreFaderListen:
3841                                 switch (Config->get_pfl_position ()) {
3842                                 case PFLFromBeforeProcessors:
3843                                         new_processors.push_front (_monitor_send);
3844                                         break;
3845                                 case PFLFromAfterProcessors:
3846                                         new_processors.insert (amp, _monitor_send);
3847                                         break;
3848                                 }
3849                                 _monitor_send->set_can_pan (false);
3850                                 break;
3851                         case AfterFaderListen:
3852                                 switch (Config->get_afl_position ()) {
3853                                 case AFLFromBeforeProcessors:
3854                                         new_processors.insert (after_amp, _monitor_send);
3855                                         break;
3856                                 case AFLFromAfterProcessors:
3857                                         new_processors.insert (new_processors.end(), _monitor_send);
3858                                         break;
3859                                 }
3860                                 _monitor_send->set_can_pan (true);
3861                                 break;
3862                         }
3863                 }  else {
3864                         new_processors.insert (new_processors.end(), _monitor_send);
3865                         _monitor_send->set_can_pan (false);
3866                 }
3867         }
3868
3869         /* MONITOR CONTROL */
3870
3871         if (_monitor_control && is_monitor ()) {
3872                 assert (!_monitor_control->display_to_user ());
3873                 new_processors.push_front (_monitor_control);
3874         }
3875
3876         /* INTERNAL RETURN */
3877
3878         /* doing this here means that any monitor control will come just after
3879            the return.
3880         */
3881
3882         if (_intreturn) {
3883                 assert (!_intreturn->display_to_user ());
3884                 new_processors.push_front (_intreturn);
3885         }
3886
3887         /* EXPORT PROCESSOR */
3888
3889         if (_capturing_processor) {
3890                 assert (!_capturing_processor->display_to_user ());
3891                 new_processors.push_front (_capturing_processor);
3892         }
3893
3894         _processors = new_processors;
3895
3896         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: setup_invisible_processors\n", _name));
3897         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3898                 DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1\n", (*i)->name ()));
3899         }
3900 }
3901
3902 void
3903 Route::unpan ()
3904 {
3905         Glib::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3906         Glib::RWLock::ReaderLock lp (_processor_lock);
3907
3908         _pannable.reset ();
3909
3910         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3911                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery>(*i);
3912                 if (d) {
3913                         d->unpan ();
3914                 }
3915         }
3916 }
3917
3918 /** If the meter point is `Custom', make a note of where the meter is.
3919  *  This is so that if the meter point is subsequently set to something else,
3920  *  and then back to custom, we can put the meter back where it was last time
3921  *  custom was enabled.
3922  *
3923  *  Must be called with the _processor_lock held.
3924  */
3925 void
3926 Route::maybe_note_meter_position ()
3927 {
3928         if (_meter_point != MeterCustom) {
3929                 return;
3930         }
3931         
3932         _custom_meter_position_noted = true;
3933         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3934                 if (boost::dynamic_pointer_cast<PeakMeter> (*i)) {
3935                         ProcessorList::iterator j = i;
3936                         ++j;
3937                         if (j != _processors.end ()) {
3938                                 _processor_after_last_custom_meter = *j;
3939                                 _last_custom_meter_was_at_end = false;
3940                         } else {
3941                                 _last_custom_meter_was_at_end = true;
3942                         }
3943                 }
3944         }
3945 }
3946
3947 boost::shared_ptr<Processor>
3948 Route::processor_by_id (PBD::ID id) const
3949 {
3950         Glib::RWLock::ReaderLock lm (_processor_lock);
3951         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3952                 if ((*i)->id() == id) {
3953                         return *i;
3954                 }
3955         }
3956
3957         return boost::shared_ptr<Processor> ();
3958 }
3959
3960 /** @return the monitoring state, or in other words what data we are pushing
3961  *  into the route (data from the inputs, data from disk or silence)
3962  */
3963 MonitorState
3964 Route::monitoring_state () const
3965 {
3966         return MonitoringInput;
3967 }
3968
3969 /** @return what we should be metering; either the data coming from the input
3970  *  IO or the data that is flowing through the route.
3971  */
3972 MeterState
3973 Route::metering_state () const
3974 {
3975         return MeteringRoute;
3976 }