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