NO-OP: Unclutter -DGraph
[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 <cassert>
26 #include <algorithm>
27
28 #include <glibmm.h>
29 #include <boost/algorithm/string.hpp>
30
31 #include "pbd/xml++.h"
32 #include "pbd/enumwriter.h"
33 #include "pbd/locale_guard.h"
34 #include "pbd/memento_command.h"
35 #include "pbd/stacktrace.h"
36 #include "pbd/types_convert.h"
37 #include "pbd/unwind.h"
38
39 #include "ardour/amp.h"
40 #include "ardour/audio_buffer.h"
41 #include "ardour/audio_track.h"
42 #include "ardour/audio_port.h"
43 #include "ardour/audioengine.h"
44 #include "ardour/boost_debug.h"
45 #include "ardour/buffer.h"
46 #include "ardour/buffer_set.h"
47 #include "ardour/capturing_processor.h"
48 #include "ardour/debug.h"
49 #include "ardour/delivery.h"
50 #include "ardour/disk_reader.h"
51 #include "ardour/disk_writer.h"
52 #include "ardour/event_type_map.h"
53 #include "ardour/gain_control.h"
54 #include "ardour/internal_return.h"
55 #include "ardour/internal_send.h"
56 #include "ardour/meter.h"
57 #include "ardour/delayline.h"
58 #include "ardour/midi_buffer.h"
59 #include "ardour/midi_port.h"
60 #include "ardour/midi_track.h"
61 #include "ardour/monitor_control.h"
62 #include "ardour/monitor_processor.h"
63 #include "ardour/pannable.h"
64 #include "ardour/panner.h"
65 #include "ardour/panner_shell.h"
66 #include "ardour/parameter_descriptor.h"
67 #include "ardour/phase_control.h"
68 #include "ardour/plugin_insert.h"
69 #include "ardour/polarity_processor.h"
70 #include "ardour/port.h"
71 #include "ardour/port_insert.h"
72 #include "ardour/processor.h"
73 #include "ardour/profile.h"
74 #include "ardour/revision.h"
75 #include "ardour/route.h"
76 #include "ardour/route_group.h"
77 #include "ardour/send.h"
78 #include "ardour/session.h"
79 #include "ardour/solo_control.h"
80 #include "ardour/solo_isolate_control.h"
81 #include "ardour/types_convert.h"
82 #include "ardour/unknown_processor.h"
83 #include "ardour/utils.h"
84 #include "ardour/vca.h"
85
86 #include "pbd/i18n.h"
87
88 using namespace std;
89 using namespace ARDOUR;
90 using namespace PBD;
91
92 PBD::Signal3<int,boost::shared_ptr<Route>, boost::shared_ptr<PluginInsert>, Route::PluginSetupOptions > Route::PluginSetup;
93
94 /** Base class for all routable/mixable objects (tracks and busses) */
95 Route::Route (Session& sess, string name, PresentationInfo::Flag flag, DataType default_type)
96         : Stripable (sess, name, PresentationInfo (flag))
97         , GraphNode (sess._process_graph)
98         , Muteable (sess, name)
99         , _active (true)
100         , _signal_latency (0)
101         , _disk_io_point (DiskIOPreFader)
102         , _pending_process_reorder (0)
103         , _pending_signals (0)
104         , _meter_point (MeterPostFader)
105         , _pending_meter_point (MeterPostFader)
106         , _meter_type (MeterPeak)
107         , _denormal_protection (false)
108         , _recordable (true)
109         , _have_internal_generator (false)
110         , _default_type (default_type)
111         , _loop_location (NULL)
112         , _track_number (0)
113         , _strict_io (false)
114         , _in_configure_processors (false)
115         , _initial_io_setup (false)
116         , _in_sidechain_setup (false)
117         , _custom_meter_position_noted (false)
118         , _pinmgr_proxy (0)
119         , _patch_selector_dialog (0)
120 {
121         processor_max_streams.reset();
122 }
123
124 boost::weak_ptr<Route>
125 Route::weakroute () {
126         return boost::weak_ptr<Route> (boost::dynamic_pointer_cast<Route> (shared_from_this ()));
127 }
128
129 int
130 Route::init ()
131 {
132         /* set default meter type */
133         if (is_master()) {
134                 _meter_type = Config->get_meter_type_master ();
135         }
136         else if (dynamic_cast<Track*>(this)) {
137                 _meter_type = Config->get_meter_type_track ();
138         } else {
139                 _meter_type = Config->get_meter_type_bus ();
140         }
141
142         /* add standard controls */
143
144         _gain_control.reset (new GainControl (_session, GainAutomation));
145         _trim_control.reset (new GainControl (_session, TrimAutomation));
146         /* While the route has-a gain-control for consistency with Stripable and VCA
147          * ownership is handed over to the Amp Processor which manages the
148          * state of the Control and AutomationList as part of its
149          * Automatable API. -- Don't call add_control () here.
150          */
151
152         _solo_control.reset (new SoloControl (_session, X_("solo"), *this, *this));
153         add_control (_solo_control);
154         _solo_control->Changed.connect_same_thread (*this, boost::bind (&Route::solo_control_changed, this, _1, _2));
155
156         _mute_control.reset (new MuteControl (_session, X_("mute"), *this));
157         add_control (_mute_control);
158
159         _phase_control.reset (new PhaseControl (_session, X_("phase")));
160         add_control (_phase_control);
161
162         _solo_isolate_control.reset (new SoloIsolateControl (_session, X_("solo-iso"), *this, *this));
163         add_control (_solo_isolate_control);
164
165         _solo_safe_control.reset (new SoloSafeControl (_session, X_("solo-safe")));
166         add_control (_solo_safe_control);
167
168         /* panning */
169
170         if (!(_presentation_info.flags() & PresentationInfo::MonitorOut)) {
171                 _pannable.reset (new Pannable (_session));
172         }
173
174         /* input and output objects */
175
176         _input.reset (new IO (_session, _name, IO::Input, _default_type));
177         _output.reset (new IO (_session, _name, IO::Output, _default_type));
178
179         _input->changed.connect_same_thread (*this, boost::bind (&Route::input_change_handler, this, _1, _2));
180         _input->PortCountChanging.connect_same_thread (*this, boost::bind (&Route::input_port_count_changing, this, _1));
181
182         _output->changed.connect_same_thread (*this, boost::bind (&Route::output_change_handler, this, _1, _2));
183         _output->PortCountChanging.connect_same_thread (*this, boost::bind (&Route::output_port_count_changing, this, _1));
184
185         /* add the amp/fader processor.
186          * it should be the first processor to be added on every route.
187          */
188
189         _amp.reset (new Amp (_session, X_("Fader"), _gain_control, true));
190         _amp->activate ();
191         _amp->set_owner (this);
192
193         _polarity.reset (new PolarityProcessor (_session, _phase_control));
194         _polarity->activate();
195         _polarity->set_owner (this);
196
197         if (is_monitor ()) {
198                 _amp->set_display_name (_("Monitor"));
199         }
200
201         if (!is_master() && !is_monitor() && !is_auditioner()) {
202                 _delayline.reset (new DelayLine (_session, name ()));
203         }
204
205         /* and input trim */
206
207         _trim.reset (new Amp (_session, X_("Trim"), _trim_control, false));
208         _trim->set_display_to_user (false);
209
210         if (dynamic_cast<AudioTrack*>(this)) {
211                 /* we can't do this in the AudioTrack's constructor
212                  * because _trim does not exit then
213                  */
214                 _trim->activate();
215         }
216         else if (!dynamic_cast<Track*>(this) && ! (is_monitor() || is_auditioner())) {
217                 /* regular bus */
218                 _trim->activate();
219         }
220
221         /* create standard processors: meter, main outs, monitor out;
222            they will be added to _processors by setup_invisible_processors ()
223         */
224
225         _meter.reset (new PeakMeter (_session, _name));
226         _meter->set_owner (this);
227         _meter->set_display_to_user (false);
228         _meter->activate ();
229
230         _main_outs.reset (new Delivery (_session, _output, _pannable, _mute_master, _name, Delivery::Main));
231         _main_outs->activate ();
232
233         if (is_monitor()) {
234                 /* where we listen to tracks */
235                 _intreturn.reset (new InternalReturn (_session));
236                 _intreturn->activate ();
237
238                 /* the thing that provides proper control over a control/monitor/listen bus
239                    (such as per-channel cut, dim, solo, invert, etc).
240                 */
241                 _monitor_control.reset (new MonitorProcessor (_session));
242                 _monitor_control->activate ();
243         }
244         if (_presentation_info.flags() & PresentationInfo::FoldbackBus) {
245                 panner_shell()->select_panner_by_uri ("http://ardour.org/plugin/panner_balance");
246         }
247
248         /* now set up processor chain and invisible processors */
249         {
250                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
251                 {
252                         Glib::Threads::RWLock::WriterLock lm (_processor_lock);
253                         _processors.push_back (_amp);
254                 }
255                 if (!_session.loading()) {
256                         configure_processors (0);
257                 }
258         }
259
260         return 0;
261 }
262
263 Route::~Route ()
264 {
265         DEBUG_TRACE (DEBUG::Destruction, string_compose ("route %1 destructor\n", _name));
266
267         /* do this early so that we don't get incoming signals as we are going through destruction
268          */
269
270         drop_connections ();
271
272         /* don't use clear_processors here, as it depends on the session which may
273            be half-destroyed by now
274         */
275
276         Glib::Threads::RWLock::WriterLock lm (_processor_lock);
277         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
278                 (*i)->drop_references ();
279         }
280
281         _processors.clear ();
282 }
283
284 string
285 Route::ensure_track_or_route_name (string newname) const
286 {
287         while (!_session.io_name_is_legal (newname)) {
288                 newname = bump_name_once (newname, ' ');
289                 if (newname == name()) {
290                         break;
291                 }
292         }
293         return newname;
294 }
295
296 void
297 Route::set_trim (gain_t val, Controllable::GroupControlDisposition /* group override */)
298 {
299         // TODO route group, see set_gain()
300         // _trim_control->route_set_value (val);
301 }
302
303 /** Process this route for one (sub) cycle (process thread)
304  *
305  * @param bufs Scratch buffers to use for the signal path
306  * @param start_sample Initial transport sample
307  * @param end_sample Final transport sample
308  * @param nframes Number of samples to output (to ports)
309  *
310  * Note that (end_sample - start_sample) may not be equal to nframes when the
311  * transport speed isn't 1.0 (eg varispeed).
312  */
313 void
314 Route::process_output_buffers (BufferSet& bufs,
315                                samplepos_t start_sample, samplepos_t end_sample, pframes_t nframes,
316                                bool gain_automation_ok, bool run_disk_reader)
317 {
318         /* Caller must hold process lock */
319         assert (!AudioEngine::instance()->process_lock().trylock());
320
321         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
322         if (!lm.locked()) {
323                 // can this actually happen?
324                 // Places that need a WriterLock on (_processor_lock) must also take the process-lock.
325                 bufs.silence (nframes, 0);
326                 assert (0); // ...one way to find out.
327                 return;
328         }
329
330         /* We should offset the route-owned ctrls by the given latency, however
331          * this only affects Mute. Other route-owned controls (solo, polarity..)
332          * are not automatable.
333          *
334          * Mute has its own issues since there's not a single mute-point,
335          * but in general
336          */
337         automation_run (start_sample, nframes);
338
339         if (_pannable) {
340                 _pannable->automation_run (start_sample + _signal_latency, nframes);
341         }
342
343         /* figure out if we're going to use gain automation */
344         if (gain_automation_ok) {
345                 _amp->set_gain_automation_buffer (_session.gain_automation_buffer ());
346                 _amp->setup_gain_automation (
347                                 start_sample + _amp->output_latency (),
348                                 end_sample + _amp->output_latency (),
349                                 nframes);
350
351                 _trim->set_gain_automation_buffer (_session.trim_automation_buffer ());
352                 _trim->setup_gain_automation (
353                                 start_sample + _trim->output_latency (),
354                                 end_sample + _trim->output_latency (),
355                                 nframes);
356         }
357
358         /* We align the playhead to output. The user hears what the clock says:
359          * When the playhead/clock says 1:00:00:00 the user will hear the audio sample
360          * at 1:00:00:00. sample_start will be [sample at] 1:00:00:00
361          *
362          * e.g. clock says Time T = 0,  sample_start = 0
363          * Disk-read(play) -> latent-plugin (+10) -> fader-automation -> output (+5)
364          * -> total playback latency "disk -> out" is 15.
365          * -> at Time T= -15, the disk-reader reads sample T=0.
366          * By the Time T=0 is reached (dt=15 later) that sample is audible.
367          */
368
369         const double speed = (is_auditioner() ? 1.0 : _session.transport_speed ());
370
371         const sampleoffset_t latency_offset = _signal_latency + _output->latency ();
372         if (speed < 0) {
373                 /* when rolling backwards this can become negative */
374                 start_sample -= latency_offset;
375                 end_sample -= latency_offset;
376         } else {
377                 start_sample += latency_offset;
378                 end_sample += latency_offset;
379         }
380
381         /* Note: during intial pre-roll 'start_sample' as passed as argument can be negative.
382          * Functions calling process_output_buffers() will set  "run_disk_reader"
383          * to false if the pre-roll count-down is larger than playback_latency ().
384          *
385          * playback_latency() is guarnteed to be <= _signal_latency + _output->latency ()
386          */
387         assert (!_disk_reader || !run_disk_reader || start_sample >= 0 || speed < 0);
388
389         /* however the disk-writer may need to pick up output from other tracks
390          * during pre-roll (in particular if this route has latent effects after the disk).
391          *
392          * e.g. track 1 play -> latency A --port--> track2 capture -> latency B ---> out
393          * total pre-roll = A + B.
394          *
395          * Note the disk-writer has built-in overlap detection (it's safe to run it early)
396          * given that
397          */
398         bool run_disk_writer = false;
399         if (_disk_writer && speed > 0) {
400                 samplecnt_t latency_preroll = _session.remaining_latency_preroll ();
401                 run_disk_writer = latency_preroll < nframes + (_signal_latency + _output->latency ());
402                 if (end_sample - _disk_writer->input_latency () < _session.transport_sample ()) {
403                         run_disk_writer = true;
404                 }
405         }
406
407         /* Tell main outs what to do about monitoring.  We do this so that
408          * on a transition between monitoring states we get a de-clicking gain
409          * change in the _main_outs delivery, if config.get_use_monitor_fades()
410          * is true.
411          *
412          * We override this in the case where we have an internal generator.
413          *
414          * FIXME: when punching in/out this also depends on latency compensated time
415          * for this route. monitoring_state() does not currently handle that correctly,.
416          *
417          * Also during remaining_latency_preroll, transport_rolling () is false, but
418          * we may need to monitor disk instead.
419          */
420         MonitorState ms = monitoring_state ();
421         bool silence = _have_internal_generator ? false : (ms == MonitoringSilence);
422
423         _main_outs->no_outs_cuz_we_no_monitor (silence);
424
425         /* -------------------------------------------------------------------------------------------
426            DENORMAL CONTROL
427            ----------------------------------------------------------------------------------------- */
428         /* XXX We'll need to protect silent inputs as well as silent disk
429          * (when not monitoring input or monitoring disk and there's no region
430          * for a longer time).
431          *
432          * ...or simply drop that feature.
433          */
434         if (_denormal_protection || Config->get_denormal_protection()) {
435
436                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
437                         Sample* const sp = i->data();
438                         for (pframes_t nx = 0; nx < nframes; ++nx) {
439                                 sp[nx] += 1.0e-27f;
440                         }
441                 }
442         }
443
444
445         /* -------------------------------------------------------------------------------------------
446            and go ....
447            ----------------------------------------------------------------------------------------- */
448
449         samplecnt_t latency = 0;
450
451         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
452
453                 /* TODO check for split cycles here.
454                  *
455                  * start_frame, end_frame is adjusted by latency and may
456                  * cross loop points.
457                  */
458
459 #ifndef NDEBUG
460                 /* if it has any inputs, make sure they match */
461                 if (boost::dynamic_pointer_cast<UnknownProcessor> (*i) == 0 && (*i)->input_streams() != ChanCount::ZERO) {
462                         if (bufs.count() != (*i)->input_streams()) {
463                                 DEBUG_TRACE (
464                                         DEBUG::Processors, string_compose (
465                                                 "input port mismatch %1 bufs = %2 input for %3 = %4\n",
466                                                 _name, bufs.count(), (*i)->name(), (*i)->input_streams()
467                                                 )
468                                         );
469                         }
470                 }
471 #endif
472
473                 bool re_inject_oob_data = false;
474                 if ((*i) == _disk_reader) {
475                         /* Well now, we've made it past the disk-writer and to the disk-reader.
476                          * Time to decide what to do about monitoring.
477                          *
478                          * Even when not doing MonitoringDisk, we need to run the processors,
479                          * so that it advances its internal buffers (IFF run_disk_reader is true).
480                          *
481                          */
482                         if (ms == MonitoringDisk || ms == MonitoringSilence) {
483                                 /* this will clear out-of-band data, too (e.g. MIDI-PC, Panic etc.
484                                  * OOB data is written at the end of the cycle (nframes - 1),
485                                  * and jack does not re-order events, so we push them back later */
486                                 re_inject_oob_data = true;
487                                 bufs.silence (nframes, 0);
488                         }
489                 }
490
491                 double pspeed = speed;
492                 if ((!run_disk_reader && (*i) == _disk_reader) || (!run_disk_writer && (*i) == _disk_writer)) {
493                         /* run with speed 0, no-roll */
494                         pspeed = 0;
495                 }
496
497                 if (speed < 0) {
498                         (*i)->run (bufs, start_sample + latency, end_sample + latency, pspeed, nframes, *i != _processors.back());
499                 } else {
500                         (*i)->run (bufs, start_sample - latency, end_sample - latency, pspeed, nframes, *i != _processors.back());
501                 }
502
503                 bufs.set_count ((*i)->output_streams());
504
505                 /* Note: plugin latency may change. While the plugin does inform the session via
506                  * processor_latency_changed(). But the session may not yet have gotten around to
507                  * update the actual worste-case and update this track's _signal_latency.
508                  *
509                  * So there can be cases where adding up all latencies may not equal _signal_latency.
510                  */
511                 if ((*i)->active ()) {
512                         latency += (*i)->effective_latency ();
513                 }
514
515                 if (re_inject_oob_data) {
516                         write_out_of_band_data (bufs, nframes);
517                 }
518
519 #if 0
520                 if ((*i) == _delayline) {
521                         latency += _delayline->delay ();
522                 }
523 #endif
524         }
525 }
526
527 void
528 Route::bounce_process (BufferSet& buffers, samplepos_t start, samplecnt_t nframes,
529                 boost::shared_ptr<Processor> endpoint,
530                 bool include_endpoint, bool for_export, bool for_freeze)
531 {
532         /* If no processing is required, there's no need to go any further. */
533         if (!endpoint && !include_endpoint) {
534                 return;
535         }
536
537         samplecnt_t latency = bounce_get_latency(_amp, false, for_export, for_freeze);
538         _amp->set_gain_automation_buffer (_session.gain_automation_buffer ());
539         _amp->setup_gain_automation (start - latency, start - latency + nframes, nframes);
540
541         /* trim is always at the top, for bounce no latency compensation is needed */
542         _trim->set_gain_automation_buffer (_session.trim_automation_buffer ());
543         _trim->setup_gain_automation (start, start + nframes, nframes);
544
545         latency = 0;
546         bool seen_disk_io = false;
547         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
548
549                 if (!include_endpoint && (*i) == endpoint) {
550                         break;
551                 }
552
553                 if (!for_export && !seen_disk_io) {
554                         if (boost::dynamic_pointer_cast<DiskReader> (*i)) {
555                                 seen_disk_io = true;
556                                 buffers.set_count ((*i)->output_streams());
557                         }
558                         continue;
559                 }
560
561                 /* if we're *not* exporting, stop processing if we come across a routing processor. */
562                 if (!for_export && boost::dynamic_pointer_cast<PortInsert>(*i)) {
563                         break;
564                 }
565                 if (!for_export && for_freeze && (*i)->does_routing() && (*i)->active()) {
566                         break;
567                 }
568
569                 /* special case the panner (export outputs)
570                  * Ideally we'd only run the panner, not the delivery itself...
571                  * but panners need separate input/output buffers and some context
572                  * (panshell, panner type, etc). AFAICT there is no ill side effect
573                  * of re-using the main delivery when freewheeling/exporting a region.
574                  */
575                 if ((*i) == _main_outs) {
576                         assert ((*i)->does_routing());
577                         (*i)->run (buffers, start - latency, start - latency + nframes, 1.0, nframes, true);
578                         buffers.set_count ((*i)->output_streams());
579                 }
580
581                 /* don't run any processors that do routing.
582                  * Also don't bother with metering.
583                  */
584                 if (!(*i)->does_routing() && !boost::dynamic_pointer_cast<PeakMeter>(*i)) {
585                         (*i)->run (buffers, start - latency, start - latency + nframes, 1.0, nframes, true);
586                         buffers.set_count ((*i)->output_streams());
587                         latency += (*i)->effective_latency ();
588                 }
589
590                 if ((*i) == endpoint) {
591                         break;
592                 }
593         }
594 }
595
596 samplecnt_t
597 Route::bounce_get_latency (boost::shared_ptr<Processor> endpoint,
598                 bool include_endpoint, bool for_export, bool for_freeze) const
599 {
600         samplecnt_t latency = 0;
601         if (!endpoint && !include_endpoint) {
602                 return latency;
603         }
604
605         bool seen_disk_io = false;
606         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
607                 if (!include_endpoint && (*i) == endpoint) {
608                         break;
609                 }
610                 if (!for_export && !seen_disk_io) {
611                         if (boost::dynamic_pointer_cast<DiskReader> (*i)) {
612                                 seen_disk_io = true;
613                         }
614                         continue;
615                 }
616                 if (!for_export && boost::dynamic_pointer_cast<PortInsert>(*i)) {
617                         break;
618                 }
619                 if (!for_export && for_freeze && (*i)->does_routing() && (*i)->active()) {
620                         break;
621                 }
622                 if (!(*i)->does_routing() && !boost::dynamic_pointer_cast<PeakMeter>(*i)) {
623                         latency += (*i)->effective_latency ();
624                 }
625                 if ((*i) == endpoint) {
626                         break;
627                 }
628         }
629         return latency;
630 }
631
632 ChanCount
633 Route::bounce_get_output_streams (ChanCount &cc, boost::shared_ptr<Processor> endpoint,
634                 bool include_endpoint, bool for_export, bool for_freeze) const
635 {
636         if (!endpoint && !include_endpoint) {
637                 return cc;
638         }
639
640         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
641                 if (!include_endpoint && (*i) == endpoint) {
642                         break;
643                 }
644                 if (!for_export && boost::dynamic_pointer_cast<PortInsert>(*i)) {
645                         break;
646                 }
647                 if (!for_export && for_freeze && (*i)->does_routing() && (*i)->active()) {
648                         break;
649                 }
650                 if (!(*i)->does_routing() && !boost::dynamic_pointer_cast<PeakMeter>(*i)) {
651                         cc = (*i)->output_streams();
652                 }
653                 if ((*i) == endpoint) {
654                         break;
655                 }
656         }
657         return cc;
658 }
659
660 ChanCount
661 Route::n_process_buffers ()
662 {
663         return max (_input->n_ports(), processor_max_streams);
664 }
665
666 void
667 Route::monitor_run (samplepos_t start_sample, samplepos_t end_sample, pframes_t nframes)
668 {
669         assert (is_monitor());
670         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
671         run_route (start_sample, end_sample, nframes, true, false);
672 }
673
674 void
675 Route::run_route (samplepos_t start_sample, samplepos_t end_sample, pframes_t nframes, bool gain_automation_ok, bool run_disk_reader)
676 {
677         BufferSet& bufs (_session.get_route_buffers (n_process_buffers()));
678
679         fill_buffers_with_input (bufs, _input, nframes);
680
681         /* filter captured data before meter sees it */
682         filter_input (bufs);
683
684         if (is_monitor() && _session.listening() && !_session.is_auditioning()) {
685
686                 /* control/monitor bus ignores input ports when something is
687                    feeding the listen "stream". data will "arrive" into the
688                    route from the intreturn processor element.
689                 */
690
691                 bufs.silence (nframes, 0);
692         }
693
694         snapshot_out_of_band_data (nframes);
695         /* append immediate messages to the first MIDI buffer (thus sending it to the first output port) */
696
697         write_out_of_band_data (bufs, nframes);
698
699         /* run processor chain */
700
701         process_output_buffers (bufs, start_sample, end_sample, nframes, gain_automation_ok, run_disk_reader);
702
703         /* map events (e.g. MIDI-CC) back to control-parameters */
704         update_controls (bufs);
705
706         flush_processor_buffers_locked (nframes);
707 }
708
709 void
710 Route::set_listen (bool yn)
711 {
712         if (_monitor_send) {
713                 if (_monitor_send->active() == yn) {
714                         return;
715                 }
716                 if (yn) {
717                         _monitor_send->activate ();
718                 } else {
719                         _monitor_send->deactivate ();
720                 }
721         }
722 }
723
724 void
725 Route::solo_control_changed (bool, Controllable::GroupControlDisposition)
726 {
727         /* nothing to do if we're not using AFL/PFL. But if we are, we need
728            to alter the active state of the monitor send.
729         */
730
731         if (Config->get_solo_control_is_listen_control ()) {
732                 set_listen (_solo_control->self_soloed() || _solo_control->get_masters_value());
733         }
734 }
735
736 void
737 Route::push_solo_isolate_upstream (int32_t delta)
738 {
739         /* forward propagate solo-isolate status to everything fed by this route, but not those via sends only */
740
741         boost::shared_ptr<RouteList> routes = _session.get_routes ();
742         for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
743
744                 if ((*i).get() == this || !(*i)->can_solo()) {
745                         continue;
746                 }
747
748                 bool sends_only;
749                 bool does_feed = feeds (*i, &sends_only);
750
751                 if (does_feed && !sends_only) {
752                         (*i)->solo_isolate_control()->mod_solo_isolated_by_upstream (delta);
753                 }
754         }
755 }
756
757 void
758 Route::push_solo_upstream (int delta)
759 {
760         DEBUG_TRACE (DEBUG::Solo, string_compose("\t ... INVERT push from %1\n", _name));
761         for (FedBy::iterator i = _fed_by.begin(); i != _fed_by.end(); ++i) {
762                 if (i->sends_only) {
763                         continue;
764                 }
765                 boost::shared_ptr<Route> sr (i->r.lock());
766                 if (sr) {
767                         sr->solo_control()->mod_solo_by_others_downstream (-delta);
768                 }
769         }
770 }
771
772 #if 0
773 static void
774 dump_processors(const string& name, const list<boost::shared_ptr<Processor> >& procs)
775 {
776         cerr << name << " {" << endl;
777         for (list<boost::shared_ptr<Processor> >::const_iterator p = procs.begin();
778                         p != procs.end(); ++p) {
779                 cerr << "\t" << (*p)->name() << " ID = " << (*p)->id() << " @ " << (*p) << endl;
780         }
781         cerr << "}" << endl;
782 }
783 #endif
784
785 /** Supposing that we want to insert a Processor at a given Placement, return
786  *  the processor to add the new one before (or 0 to add at the end).
787  */
788 boost::shared_ptr<Processor>
789 Route::before_processor_for_placement (Placement p)
790 {
791         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
792
793         ProcessorList::iterator loc;
794
795         if (p == PreFader) {
796                 /* generic pre-fader: insert immediately before the amp */
797                 loc = find (_processors.begin(), _processors.end(), _amp);
798         } else {
799                 /* generic post-fader: insert right before the main outs */
800                 loc = find (_processors.begin(), _processors.end(), _main_outs);
801         }
802
803         return loc != _processors.end() ? *loc : boost::shared_ptr<Processor> ();
804 }
805
806 /** Supposing that we want to insert a Processor at a given index, return
807  *  the processor to add the new one before (or 0 to add at the end).
808  */
809 boost::shared_ptr<Processor>
810 Route::before_processor_for_index (int index)
811 {
812         if (index == -1) {
813                 return boost::shared_ptr<Processor> ();
814         }
815
816         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
817
818         ProcessorList::iterator i = _processors.begin ();
819         int j = 0;
820         while (i != _processors.end() && j < index) {
821                 if ((*i)->display_to_user()) {
822                         ++j;
823                 }
824
825                 ++i;
826         }
827
828         return (i != _processors.end() ? *i : boost::shared_ptr<Processor> ());
829 }
830
831 /** Add a processor either pre- or post-fader
832  *  @return 0 on success, non-0 on failure.
833  */
834 int
835 Route::add_processor (boost::shared_ptr<Processor> processor, Placement placement, ProcessorStreams* err, bool activation_allowed)
836 {
837         return add_processor (processor, before_processor_for_placement (placement), err, activation_allowed);
838 }
839
840
841 /** Add a processor to a route such that it ends up with a given index into the visible processors.
842  *  @param index Index to add the processor at, or -1 to add at the end of the list.
843  *  @return 0 on success, non-0 on failure.
844  */
845 int
846 Route::add_processor_by_index (boost::shared_ptr<Processor> processor, int index, ProcessorStreams* err, bool activation_allowed)
847 {
848         return add_processor (processor, before_processor_for_index (index), err, activation_allowed);
849 }
850
851 /** Add a processor to the route.
852  *  @param before An existing processor in the list, or 0; the new processor will be inserted immediately before it (or at the end).
853  *  @return 0 on success, non-0 on failure.
854  */
855 int
856 Route::add_processor (boost::shared_ptr<Processor> processor, boost::shared_ptr<Processor> before, ProcessorStreams* err, bool activation_allowed)
857 {
858         assert (processor != _meter);
859         assert (processor != _main_outs);
860
861         DEBUG_TRACE (DEBUG::Processors, string_compose (
862                              "%1 adding processor %2\n", name(), processor->name()));
863
864         ProcessorList pl;
865
866         pl.push_back (processor);
867         int rv = add_processors (pl, before, err);
868
869         if (rv) {
870                 return rv;
871         }
872
873         if (activation_allowed && (!_session.get_bypass_all_loaded_plugins () || !processor->display_to_user ())) {
874                 processor->activate ();
875         }
876
877         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (processor);
878         if (pi) {
879                 pi->update_sidechain_name ();
880         }
881
882         return 0;
883 }
884
885 void
886 Route::processor_selfdestruct (boost::weak_ptr<Processor> wp)
887 {
888         /* We cannot destruct the processor here (usually RT-thread
889          * with various locks held - in case of sends also io_locks).
890          * Queue for deletion in low-priority thread.
891          */
892         Glib::Threads::Mutex::Lock lx (selfdestruct_lock);
893         selfdestruct_sequence.push_back (wp);
894 }
895
896 bool
897 Route::add_processor_from_xml_2X (const XMLNode& node, int version)
898 {
899         XMLProperty const * prop;
900
901         try {
902                 boost::shared_ptr<Processor> processor;
903
904                 /* bit of a hack: get the `placement' property from the <Redirect> tag here
905                    so that we can add the processor in the right place (pre/post-fader)
906                 */
907
908                 XMLNodeList const & children = node.children ();
909                 XMLNodeList::const_iterator i = children.begin ();
910
911                 while (i != children.end() && (*i)->name() != X_("Redirect")) {
912                         ++i;
913                 }
914
915                 Placement placement = PreFader;
916
917                 if (i != children.end()) {
918                         if ((prop = (*i)->property (X_("placement"))) != 0) {
919                                 placement = Placement (string_2_enum (prop->value(), placement));
920                         }
921                 }
922
923                 if (node.name() == "Insert") {
924
925                         if ((prop = node.property ("type")) != 0) {
926
927                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" ||
928                                                 prop->value() == "lv2" ||
929                                                 prop->value() == "windows-vst" ||
930                                                 prop->value() == "mac-vst" ||
931                                                 prop->value() == "lxvst" ||
932                                                 prop->value() == "audiounit") {
933
934                                         if (_session.get_disable_all_loaded_plugins ()) {
935                                                 processor.reset (new UnknownProcessor (_session, node));
936                                         } else {
937                                                 processor.reset (new PluginInsert (_session));
938                                                 processor->set_owner (this);
939                                         }
940
941                                 } else {
942
943                                         processor.reset (new PortInsert (_session, _pannable, _mute_master));
944                                 }
945
946                         }
947
948                 } else if (node.name() == "Send") {
949
950                         boost::shared_ptr<Pannable> sendpan (new Pannable (_session));
951                         processor.reset (new Send (_session, sendpan, _mute_master));
952
953                 } else {
954
955                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), node.name()) << endmsg;
956                         return false;
957                 }
958
959                 if (processor->set_state (node, version)) {
960                         return false;
961                 }
962
963                 //A2 uses the "active" flag in the toplevel redirect node, not in the child plugin/IO
964                 if (i != children.end()) {
965                         if ((prop = (*i)->property (X_("active"))) != 0) {
966                                 if (string_to<bool> (prop->value()) && (!_session.get_bypass_all_loaded_plugins () || !processor->display_to_user ()))
967                                         processor->activate();
968                                 else
969                                         processor->deactivate();
970                         }
971                 }
972
973                 return (add_processor (processor, placement, 0, false) == 0);
974         }
975
976         catch (failed_constructor &err) {
977                 warning << _("processor could not be created. Ignored.") << endmsg;
978                 return false;
979         }
980 }
981
982
983 inline Route::PluginSetupOptions operator|= (Route::PluginSetupOptions& a, const Route::PluginSetupOptions& b) {
984         return a = static_cast<Route::PluginSetupOptions> (static_cast <int>(a) | static_cast<int> (b));
985 }
986
987 inline Route::PluginSetupOptions operator&= (Route::PluginSetupOptions& a, const Route::PluginSetupOptions& b) {
988         return a = static_cast<Route::PluginSetupOptions> (static_cast <int>(a) & static_cast<int> (b));
989 }
990
991 int
992 Route::add_processors (const ProcessorList& others, boost::shared_ptr<Processor> before, ProcessorStreams* err)
993 {
994         ProcessorList::iterator loc;
995         boost::shared_ptr <PluginInsert> fanout;
996
997         if (g_atomic_int_get (&_pending_process_reorder)) {
998                 /* we need to flush any pending re-order changes */
999                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1000                 apply_processor_changes_rt ();
1001         }
1002
1003         if (before) {
1004                 loc = find(_processors.begin(), _processors.end(), before);
1005                 if (loc == _processors.end ()) {
1006                         return 1;
1007                 }
1008         } else {
1009                 /* nothing specified - at end */
1010                 loc = _processors.end ();
1011         }
1012
1013         if (others.empty()) {
1014                 return 0;
1015         }
1016
1017         ProcessorList to_skip;
1018
1019         // check if there's an instrument to replace or configure
1020         for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
1021                 boost::shared_ptr<PluginInsert> pi;
1022                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) == 0) {
1023                         continue;
1024                 }
1025                 if (!pi->plugin ()->get_info ()->is_instrument ()) {
1026                         continue;
1027                 }
1028                 boost::shared_ptr<Processor> instrument = the_instrument ();
1029                 ChanCount in (DataType::MIDI, 1);
1030                 ChanCount out (DataType::AUDIO, 2); // XXX route's out?!
1031
1032                 PluginSetupOptions flags = None;
1033                 if (instrument) {
1034                         flags |= CanReplace;
1035                         in = instrument->input_streams ();
1036                         out = instrument->output_streams ();
1037                 }
1038                 if (pi->has_output_presets (in, out)) {
1039                         flags |= MultiOut;
1040                 }
1041
1042                 pi->set_strict_io (_strict_io);
1043
1044                 if (is_auditioner()) {
1045                         continue;
1046                 }
1047
1048                 PluginSetupOptions mask = None;
1049                 if (Config->get_ask_replace_instrument ()) {
1050                         mask |= CanReplace;
1051                 }
1052                 if (Config->get_ask_setup_instrument ()) {
1053                         mask |= MultiOut;
1054                 }
1055
1056                 flags &= mask;
1057
1058                 if (flags != None) {
1059                         boost::optional<int> rv = PluginSetup (boost::dynamic_pointer_cast<Route>(shared_from_this ()), pi, flags);  /* EMIT SIGNAL */
1060                         int mode = rv.get_value_or (0);
1061                         switch (mode & 3) {
1062                                 case 1:
1063                                         to_skip.push_back (*i); // don't add this one;
1064                                         break;
1065                                 case 2:
1066                                         replace_processor (instrument, *i, err);
1067                                         to_skip.push_back (*i);
1068                                         break;
1069                                 default:
1070                                         break;
1071                         }
1072                         if ((mode & 5) == 4) {
1073                                 fanout = pi;
1074                         }
1075                 }
1076         }
1077
1078         {
1079                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1080                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1081                 ProcessorState pstate (this);
1082
1083                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
1084
1085                         if (*i == _meter) {
1086                                 continue;
1087                         }
1088                         ProcessorList::iterator check = find (to_skip.begin(), to_skip.end(), *i);
1089                         if (check != to_skip.end()) {
1090                                 continue;
1091                         }
1092
1093                         boost::shared_ptr<PluginInsert> pi;
1094
1095                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1096                                 pi->set_strict_io (_strict_io);
1097                         }
1098
1099                         if (*i == _amp) {
1100                                 /* Ensure that only one amp is in the list at any time */
1101                                 ProcessorList::iterator check = find (_processors.begin(), _processors.end(), *i);
1102                                 if (check != _processors.end()) {
1103                                         if (before == _amp) {
1104                                                 /* Already in position; all is well */
1105                                                 continue;
1106                                         } else {
1107                                                 _processors.erase (check);
1108                                         }
1109                                 }
1110                         }
1111
1112                         assert (find (_processors.begin(), _processors.end(), *i) == _processors.end ());
1113
1114                         _processors.insert (loc, *i);
1115                         (*i)->set_owner (this);
1116
1117                         {
1118                                 if (configure_processors_unlocked (err, &lm)) {
1119                                         pstate.restore ();
1120                                         configure_processors_unlocked (0, &lm); // it worked before we tried to add it ...
1121                                         return -1;
1122                                 }
1123                         }
1124
1125                         if (pi && pi->has_sidechain ()) {
1126                                 pi->sidechain_input ()->changed.connect_same_thread (*this, boost::bind (&Route::sidechain_change_handler, this, _1, _2));
1127                         }
1128
1129                         if ((*i)->active()) {
1130                                 // emit ActiveChanged() and latency_changed() if needed
1131                                 (*i)->activate ();
1132                         }
1133
1134                         (*i)->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false));
1135
1136                         boost::shared_ptr<Send> send;
1137                         if ((send = boost::dynamic_pointer_cast<Send> (*i))) {
1138                                 send->SelfDestruct.connect_same_thread (*this,
1139                                                 boost::bind (&Route::processor_selfdestruct, this, boost::weak_ptr<Processor> (*i)));
1140                         }
1141                 }
1142
1143                 for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
1144                         boost::shared_ptr<PluginInsert> pi;
1145
1146                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1147                                 if (pi->has_no_inputs ()) {
1148                                         _have_internal_generator = true;
1149                                         break;
1150                                 }
1151                         }
1152                 }
1153
1154                 _output->unset_user_latency ();
1155         }
1156
1157         reset_instrument_info ();
1158         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1159         set_processor_positions ();
1160
1161         if (fanout && fanout->configured ()
1162                         && fanout->output_streams().n_audio() > 2
1163                         && boost::dynamic_pointer_cast<PluginInsert> (the_instrument ()) == fanout) {
1164                 fan_out (); /* EMIT SIGNAL */
1165         }
1166         return 0;
1167 }
1168
1169 void
1170 Route::placement_range(Placement p, ProcessorList::iterator& start, ProcessorList::iterator& end)
1171 {
1172         if (p == PreFader) {
1173                 start = _processors.begin();
1174                 end = find(_processors.begin(), _processors.end(), _amp);
1175         } else {
1176                 start = find(_processors.begin(), _processors.end(), _amp);
1177                 ++start;
1178                 end = _processors.end();
1179         }
1180 }
1181
1182 /** Turn off all processors with a given placement
1183  * @param p Placement of processors to disable
1184  */
1185 void
1186 Route::disable_processors (Placement p)
1187 {
1188         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1189
1190         ProcessorList::iterator start, end;
1191         placement_range(p, start, end);
1192
1193         for (ProcessorList::iterator i = start; i != end; ++i) {
1194                 (*i)->enable (false);
1195         }
1196
1197         _session.set_dirty ();
1198 }
1199
1200 /** Turn off all redirects
1201  */
1202 void
1203 Route::disable_processors ()
1204 {
1205         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1206
1207         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1208                 (*i)->enable (false);
1209         }
1210
1211         _session.set_dirty ();
1212 }
1213
1214 /** Turn off all redirects with a given placement
1215  * @param p Placement of redirects to disable
1216  */
1217 void
1218 Route::disable_plugins (Placement p)
1219 {
1220         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1221
1222         ProcessorList::iterator start, end;
1223         placement_range(p, start, end);
1224
1225         for (ProcessorList::iterator i = start; i != end; ++i) {
1226                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1227                         (*i)->enable (false);
1228                 }
1229         }
1230
1231         _session.set_dirty ();
1232 }
1233
1234 /** Turn off all plugins
1235  */
1236 void
1237 Route::disable_plugins ()
1238 {
1239         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1240
1241         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1242                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1243                         (*i)->enable (false);
1244                 }
1245         }
1246
1247         _session.set_dirty ();
1248 }
1249
1250
1251 void
1252 Route::ab_plugins (bool forward)
1253 {
1254         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1255
1256         if (forward) {
1257
1258                 /* forward = turn off all active redirects, and mark them so that the next time
1259                    we go the other way, we will revert them
1260                 */
1261
1262                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1263                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1264                                 continue;
1265                         }
1266                         if (!(*i)->display_to_user ()) {
1267                                 continue;
1268                         }
1269 #ifdef MIXBUS
1270                         if (boost::dynamic_pointer_cast<PluginInsert> (*i)->is_channelstrip()) {
1271                                 continue;
1272                         }
1273 #endif
1274
1275                         if ((*i)->enabled ()) {
1276                                 (*i)->enable (false);
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                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1289                                 continue;
1290                         }
1291                         if (!(*i)->display_to_user ()) {
1292                                 continue;
1293                         }
1294 #ifdef MIXBUS
1295                         if (boost::dynamic_pointer_cast<PluginInsert> (*i)->is_channelstrip()) {
1296                                 continue;
1297                         }
1298 #endif
1299
1300                         (*i)->enable ((*i)->get_next_ab_is_active ());
1301                 }
1302         }
1303
1304         _session.set_dirty ();
1305 }
1306
1307
1308 /** Remove processors with a given placement.
1309  * @param p Placement of processors to remove.
1310  */
1311 void
1312 Route::clear_processors (Placement p)
1313 {
1314         if (!_session.engine().running()) {
1315                 return;
1316         }
1317
1318         bool already_deleting = _session.deletion_in_progress();
1319         if (!already_deleting) {
1320                 _session.set_deletion_in_progress();
1321         }
1322
1323         ProcessorList old_list = _processors;
1324         {
1325                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1326                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1327                 ProcessorList new_list;
1328                 ProcessorStreams err;
1329                 bool seen_amp = false;
1330
1331                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1332
1333                         if (*i == _amp) {
1334                                 seen_amp = true;
1335                         }
1336
1337                         if (is_internal_processor (*i)) {
1338
1339                                 /* you can't remove these */
1340
1341                                 new_list.push_back (*i);
1342
1343                         } else {
1344                                 if (seen_amp) {
1345
1346                                         switch (p) {
1347                                         case PreFader:
1348                                                 new_list.push_back (*i);
1349                                                 break;
1350                                         case PostFader:
1351                                                 (*i)->drop_references ();
1352                                                 break;
1353                                         }
1354
1355                                 } else {
1356
1357                                         switch (p) {
1358                                         case PreFader:
1359                                                 (*i)->drop_references ();
1360                                                 break;
1361                                         case PostFader:
1362                                                 new_list.push_back (*i);
1363                                                 break;
1364                                         }
1365                                 }
1366                         }
1367                 }
1368
1369                 _processors = new_list;
1370                 configure_processors_unlocked (&err, &lm); // this can't fail
1371         }
1372         /* drop references w/o process-lock (I/O procs may re-take it in ~IO() */
1373         old_list.clear ();
1374
1375         processor_max_streams.reset();
1376         _have_internal_generator = false;
1377         reset_instrument_info ();
1378         set_processor_positions ();
1379
1380         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1381
1382         if (!already_deleting) {
1383                 _session.clear_deletion_in_progress();
1384         }
1385 }
1386
1387 bool
1388 Route::is_internal_processor (boost::shared_ptr<Processor> p) const
1389 {
1390         if (p == _amp || p == _meter || p == _main_outs || p == _delayline || p == _trim || p == _polarity) {
1391                 return true;
1392         }
1393 #ifdef MIXBUS
1394         if (p == _ch_pre || p == _ch_post || p == _ch_eq  || p == _ch_comp) {
1395                 return true;
1396         }
1397 #endif
1398         return false;
1399 }
1400
1401 int
1402 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err, bool need_process_lock)
1403 {
1404         // TODO once the export point can be configured properly, do something smarter here
1405         if (processor == _capturing_processor) {
1406                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1407                 if (need_process_lock) {
1408                         lx.acquire();
1409                 }
1410
1411                 _capturing_processor.reset();
1412
1413                 if (need_process_lock) {
1414                         lx.release();
1415                 }
1416         }
1417
1418         /* these can never be removed */
1419
1420         if (is_internal_processor (processor)) {
1421                 return 0;
1422         }
1423
1424         if (!_session.engine().running()) {
1425                 return 1;
1426         }
1427
1428         processor_max_streams.reset();
1429
1430         {
1431                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1432                 if (need_process_lock) {
1433                         lx.acquire();
1434                 }
1435
1436                 /* Caller must hold process lock */
1437                 assert (!AudioEngine::instance()->process_lock().trylock());
1438
1439                 Glib::Threads::RWLock::WriterLock lm (_processor_lock); // XXX deadlock after export
1440
1441                 ProcessorState pstate (this);
1442
1443                 ProcessorList::iterator i;
1444                 bool removed = false;
1445
1446                 for (i = _processors.begin(); i != _processors.end(); ) {
1447                         if (*i == processor) {
1448
1449                                 /* move along, see failure case for configure_processors()
1450                                    where we may need to reconfigure the processor.
1451                                 */
1452
1453                                 /* stop redirects that send signals to JACK ports
1454                                    from causing noise as a result of no longer being
1455                                    run.
1456                                 */
1457
1458                                 boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor> (*i);
1459                                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*i);
1460
1461                                 if (pi != 0) {
1462                                         assert (iop == 0);
1463                                         iop = pi->sidechain();
1464                                 }
1465
1466                                 if (iop != 0) {
1467                                         iop->disconnect ();
1468                                 }
1469
1470                                 i = _processors.erase (i);
1471                                 removed = true;
1472                                 break;
1473
1474                         } else {
1475                                 ++i;
1476                         }
1477
1478                         _output->unset_user_latency ();
1479                 }
1480
1481                 if (!removed) {
1482                         /* what? */
1483                         return 1;
1484                 }
1485
1486                 if (configure_processors_unlocked (err, &lm)) {
1487                         pstate.restore ();
1488                         /* we know this will work, because it worked before :) */
1489                         configure_processors_unlocked (0, &lm);
1490                         return -1;
1491                 }
1492
1493                 _have_internal_generator = false;
1494
1495                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1496                         boost::shared_ptr<PluginInsert> pi;
1497
1498                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1499                                 if (pi->has_no_inputs ()) {
1500                                         _have_internal_generator = true;
1501                                         break;
1502                                 }
1503                         }
1504                 }
1505                 if (need_process_lock) {
1506                         lx.release();
1507                 }
1508         }
1509
1510         reset_instrument_info ();
1511         processor->drop_references ();
1512         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1513         set_processor_positions ();
1514
1515         return 0;
1516 }
1517
1518 int
1519 Route::replace_processor (boost::shared_ptr<Processor> old, boost::shared_ptr<Processor> sub, ProcessorStreams* err)
1520 {
1521         /* these can never be removed */
1522         if (is_internal_processor (old)) {
1523                 return 1;
1524         }
1525         /* and can't be used as substitute, either */
1526         if (is_internal_processor (sub)) {
1527                 return 1;
1528         }
1529
1530         /* I/Os are out, too */
1531         if (boost::dynamic_pointer_cast<IOProcessor> (old) || boost::dynamic_pointer_cast<IOProcessor> (sub)) {
1532                 return 1;
1533         }
1534
1535         /* this function cannot be used to swap/reorder processors */
1536         if (find (_processors.begin(), _processors.end(), sub) != _processors.end ()) {
1537                 return 1;
1538         }
1539
1540         if (!AudioEngine::instance()->running() || !old || !sub) {
1541                 return 1;
1542         }
1543
1544         /* ensure that sub is not owned by another route */
1545         if (sub->owner ()) {
1546                 return 1;
1547         }
1548
1549         {
1550                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1551                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1552                 ProcessorState pstate (this);
1553
1554                 assert (find (_processors.begin(), _processors.end(), sub) == _processors.end ());
1555
1556                 ProcessorList::iterator i;
1557                 bool replaced = false;
1558                 bool enable = old->enabled ();
1559
1560                 for (i = _processors.begin(); i != _processors.end(); ) {
1561                         if (*i == old) {
1562                                 i = _processors.erase (i);
1563                                 _processors.insert (i, sub);
1564                                 sub->set_owner (this);
1565                                 replaced = true;
1566                                 break;
1567                         } else {
1568                                 ++i;
1569                         }
1570                 }
1571
1572                 if (!replaced) {
1573                         return 1;
1574                 }
1575
1576                 if (_strict_io) {
1577                         boost::shared_ptr<PluginInsert> pi;
1578                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(sub)) != 0) {
1579                                 pi->set_strict_io (true);
1580                         }
1581                 }
1582
1583                 if (configure_processors_unlocked (err, &lm)) {
1584                         pstate.restore ();
1585                         configure_processors_unlocked (0, &lm);
1586                         return -1;
1587                 }
1588
1589                 _have_internal_generator = false;
1590
1591                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1592                         boost::shared_ptr<PluginInsert> pi;
1593                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1594                                 if (pi->has_no_inputs ()) {
1595                                         _have_internal_generator = true;
1596                                         break;
1597                                 }
1598                         }
1599                 }
1600
1601                 if (enable) {
1602                         sub->enable (true);
1603                 }
1604
1605                 sub->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false));
1606                 _output->unset_user_latency ();
1607         }
1608
1609         reset_instrument_info ();
1610         old->drop_references ();
1611         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1612         set_processor_positions ();
1613         return 0;
1614 }
1615
1616 int
1617 Route::remove_processors (const ProcessorList& to_be_deleted, ProcessorStreams* err)
1618 {
1619         ProcessorList deleted;
1620
1621         if (!_session.engine().running()) {
1622                 return 1;
1623         }
1624
1625         processor_max_streams.reset();
1626
1627         {
1628                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1629                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1630                 ProcessorState pstate (this);
1631
1632                 ProcessorList::iterator i;
1633                 boost::shared_ptr<Processor> processor;
1634
1635                 for (i = _processors.begin(); i != _processors.end(); ) {
1636
1637                         processor = *i;
1638
1639                         /* these can never be removed */
1640
1641                         if (is_internal_processor (processor)) {
1642                                 ++i;
1643                                 continue;
1644                         }
1645
1646                         /* see if its in the list of processors to delete */
1647
1648                         if (find (to_be_deleted.begin(), to_be_deleted.end(), processor) == to_be_deleted.end()) {
1649                                 ++i;
1650                                 continue;
1651                         }
1652
1653                         /* stop IOProcessors that send to JACK ports
1654                            from causing noise as a result of no longer being
1655                            run.
1656                         */
1657
1658                         boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(processor);
1659                         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(processor);
1660                         if (pi != 0) {
1661                                 assert (iop == 0);
1662                                 iop = pi->sidechain();
1663                         }
1664
1665                         if (iop != 0) {
1666                                 iop->disconnect ();
1667                         }
1668
1669                         deleted.push_back (processor);
1670                         i = _processors.erase (i);
1671                 }
1672
1673                 if (deleted.empty()) {
1674                         /* none of those in the requested list were found */
1675                         return 0;
1676                 }
1677
1678                 _output->unset_user_latency ();
1679
1680                 if (configure_processors_unlocked (err, &lm)) {
1681                         pstate.restore ();
1682                         /* we know this will work, because it worked before :) */
1683                         configure_processors_unlocked (0, &lm);
1684                         return -1;
1685                 }
1686                 //lx.unlock();
1687
1688                 _have_internal_generator = false;
1689
1690                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1691                         boost::shared_ptr<PluginInsert> pi;
1692
1693                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1694                                 if (pi->has_no_inputs ()) {
1695                                         _have_internal_generator = true;
1696                                         break;
1697                                 }
1698                         }
1699                 }
1700         }
1701
1702         /* now try to do what we need to so that those that were removed will be deleted */
1703
1704         for (ProcessorList::iterator i = deleted.begin(); i != deleted.end(); ++i) {
1705                 (*i)->drop_references ();
1706         }
1707
1708         reset_instrument_info ();
1709         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1710         set_processor_positions ();
1711
1712         return 0;
1713 }
1714
1715 void
1716 Route::reset_instrument_info ()
1717 {
1718         boost::shared_ptr<Processor> instr = the_instrument();
1719         if (instr) {
1720                 _instrument_info.set_internal_instrument (instr);
1721         }
1722 }
1723
1724 /** Caller must hold process lock */
1725 int
1726 Route::configure_processors (ProcessorStreams* err)
1727 {
1728 #ifndef PLATFORM_WINDOWS
1729         assert (!AudioEngine::instance()->process_lock().trylock());
1730 #endif
1731
1732         if (!_in_configure_processors) {
1733                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1734                 return configure_processors_unlocked (err, &lm);
1735         }
1736
1737         return 0;
1738 }
1739
1740 ChanCount
1741 Route::input_streams () const
1742 {
1743         return _input->n_ports ();
1744 }
1745
1746 list<pair<ChanCount, ChanCount> >
1747 Route::try_configure_processors (ChanCount in, ProcessorStreams* err)
1748 {
1749         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1750
1751         return try_configure_processors_unlocked (in, err);
1752 }
1753
1754 list<pair<ChanCount, ChanCount> >
1755 Route::try_configure_processors_unlocked (ChanCount in, ProcessorStreams* err)
1756 {
1757         // Check each processor in order to see if we can configure as requested
1758         ChanCount out;
1759         list<pair<ChanCount, ChanCount> > configuration;
1760         uint32_t index = 0;
1761
1762         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configure processors\n", _name));
1763         DEBUG_TRACE (DEBUG::Processors, "{\n");
1764
1765         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++index) {
1766
1767                 if ((*p)->can_support_io_configuration(in, out)) {
1768
1769                         if (boost::dynamic_pointer_cast<Delivery> (*p)
1770                                         && boost::dynamic_pointer_cast<Delivery> (*p)->role() == Delivery::Main
1771                                         && !is_auditioner()
1772                                         && (is_monitor() || _strict_io || Profile->get_mixbus ())) {
1773                                 /* with strict I/O the panner + output are forced to
1774                                  * follow the last processor's output.
1775                                  *
1776                                  * Delivery::can_support_io_configuration() will only add ports,
1777                                  * but not remove excess ports.
1778                                  *
1779                                  * This works because the delivery only requires
1780                                  * as many outputs as there are inputs.
1781                                  * Delivery::configure_io() will do the actual removal
1782                                  * by calling _output->ensure_io()
1783                                  */
1784                                 if (!is_master() && _session.master_out () && in.n_audio() > 0) {
1785                                         /* ..but at least as many as there are master-inputs, if
1786                                          * the delivery is dealing with audio */
1787                                         // XXX this may need special-casing for mixbus (master-outputs)
1788                                         // and should maybe be a preference anyway ?!
1789                                         out = ChanCount::max (in, _session.master_out ()->n_inputs ());
1790                                 } else {
1791                                         out = in;
1792                                 }
1793                         }
1794
1795                         DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1 ID=%2 in=%3 out=%4\n",(*p)->name(), (*p)->id(), in, out));
1796                         configuration.push_back(make_pair(in, out));
1797
1798                         if (is_monitor()) {
1799                                 // restriction for Monitor Section Processors
1800                                 if (in.n_audio() != out.n_audio() || out.n_midi() > 0) {
1801                                         /* Note: The Monitor follows the master-bus and has no panner.
1802                                          *
1803                                          * The general idea is to only allow plugins that retain the channel-count
1804                                          * and plugins with MIDI in (e.g VSTs with control that will remain unconnected).
1805                                          * Then again 5.1 in, monitor stereo is a valid use-case.
1806                                          *
1807                                          * and worse: we only refuse adding plugins *here*.
1808                                          *
1809                                          * 1) stereo-master, stereo-mon, add a stereo-plugin, OK
1810                                          * 2) change master-bus, add a channel
1811                                          * 2a) monitor-secion follows
1812                                          * 3) monitor processors fail to re-reconfigure (stereo plugin)
1813                                          * 4) re-load session, monitor-processor remains unconfigured, crash.
1814                                          */
1815                                         DEBUG_TRACE (DEBUG::Processors, "Monitor: Channel configuration change.\n");
1816                                 }
1817                                 if (boost::dynamic_pointer_cast<InternalSend> (*p)) {
1818                                         // internal sends make no sense, only feedback
1819                                         DEBUG_TRACE (DEBUG::Processors, "Monitor: No Sends allowed.\n");
1820                                         return list<pair<ChanCount, ChanCount> > ();
1821                                 }
1822                                 if (boost::dynamic_pointer_cast<PortInsert> (*p)) {
1823                                         /* External Sends can be problematic. one can add/remove ports
1824                                          * there signal leaves the DAW to external monitors anyway, so there's
1825                                          * no real use for allowing them here anyway.
1826                                          */
1827                                         DEBUG_TRACE (DEBUG::Processors, "Monitor: No External Sends allowed.\n");
1828                                         return list<pair<ChanCount, ChanCount> > ();
1829                                 }
1830                                 if (boost::dynamic_pointer_cast<Send> (*p)) {
1831                                         // ditto
1832                                         DEBUG_TRACE (DEBUG::Processors, "Monitor: No Sends allowed.\n");
1833                                         return list<pair<ChanCount, ChanCount> > ();
1834                                 }
1835                         }
1836                         in = out;
1837                 } else {
1838                         if (err) {
1839                                 err->index = index;
1840                                 err->count = in;
1841                         }
1842                         DEBUG_TRACE (DEBUG::Processors, "---- CONFIGURATION FAILED.\n");
1843                         DEBUG_TRACE (DEBUG::Processors, string_compose ("---- %1 cannot support in=%2 out=%3\n", (*p)->name(), in, out));
1844                         DEBUG_TRACE (DEBUG::Processors, "}\n");
1845                         return list<pair<ChanCount, ChanCount> > ();
1846                 }
1847         }
1848
1849         DEBUG_TRACE (DEBUG::Processors, "}\n");
1850
1851         return configuration;
1852 }
1853
1854 /** Set the input/output configuration of each processor in the processors list.
1855  *  Caller must hold process lock.
1856  *  Return 0 on success, otherwise configuration is impossible.
1857  */
1858 int
1859 Route::configure_processors_unlocked (ProcessorStreams* err, Glib::Threads::RWLock::WriterLock* lm)
1860 {
1861 #ifndef PLATFORM_WINDOWS
1862         assert (!AudioEngine::instance()->process_lock().trylock());
1863 #endif
1864
1865         if (_in_configure_processors) {
1866                 return 0;
1867         }
1868
1869         /* put invisible processors where they should be */
1870         setup_invisible_processors ();
1871
1872         _in_configure_processors = true;
1873
1874         list<pair<ChanCount, ChanCount> > configuration = try_configure_processors_unlocked (input_streams (), err);
1875
1876         if (configuration.empty ()) {
1877                 _in_configure_processors = false;
1878                 return -1;
1879         }
1880
1881         ChanCount out;
1882         bool seen_mains_out = false;
1883         processor_out_streams = _input->n_ports();
1884         processor_max_streams.reset();
1885
1886         /* processor configure_io() may result in adding ports
1887          * e.g. Delivery::configure_io -> ARDOUR::IO::ensure_io ()
1888          *
1889          * with jack2 adding ports results in a graph-order callback,
1890          * which calls Session::resort_routes() and eventually
1891          * Route::direct_feeds_according_to_reality()
1892          * which takes a ReaderLock (_processor_lock).
1893          *
1894          * so we can't hold a WriterLock here until jack2 threading
1895          * is fixed.
1896          *
1897          * NB. we still hold the process lock
1898          *
1899          * (ardour's own engines do call graph-order from the
1900          * process-thread and hence do not have this issue; besides
1901          * merely adding ports won't trigger a graph-order, only
1902          * making connections does)
1903          */
1904         lm->release ();
1905
1906         // TODO check for a potential ReaderLock after ReaderLock ??
1907         Glib::Threads::RWLock::ReaderLock lr (_processor_lock);
1908
1909         list< pair<ChanCount,ChanCount> >::iterator c = configuration.begin();
1910         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++c) {
1911
1912                 if (!(*p)->configure_io(c->first, c->second)) {
1913                         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configuration failed\n", _name));
1914                         _in_configure_processors = false;
1915                         lr.release ();
1916                         lm->acquire ();
1917                         return -1;
1918                 }
1919
1920                 processor_max_streams = ChanCount::max(processor_max_streams, c->first);
1921                 processor_max_streams = ChanCount::max(processor_max_streams, c->second);
1922
1923                 boost::shared_ptr<IOProcessor> iop;
1924                 boost::shared_ptr<PluginInsert> pi;
1925                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*p)) != 0) {
1926                         /* plugins connected via Split or Hide Match may have more channels.
1927                          * route/scratch buffers are needed for all of them
1928                          * The configuration may only be a subset (both input and output)
1929                          */
1930                         processor_max_streams = ChanCount::max(processor_max_streams, pi->required_buffers());
1931                 }
1932                 else if ((iop = boost::dynamic_pointer_cast<IOProcessor>(*p)) != 0) {
1933                         processor_max_streams = ChanCount::max(processor_max_streams, iop->natural_input_streams());
1934                         processor_max_streams = ChanCount::max(processor_max_streams, iop->natural_output_streams());
1935                 }
1936                 out = c->second;
1937
1938                 if (boost::dynamic_pointer_cast<Delivery> (*p)
1939                                 && boost::dynamic_pointer_cast<Delivery> (*p)->role() == Delivery::Main) {
1940                         /* main delivery will increase port count to match input.
1941                          * the Delivery::Main is usually the last processor - followed only by
1942                          * 'MeterOutput'.
1943                          */
1944                         seen_mains_out = true;
1945                 }
1946                 if (!seen_mains_out) {
1947                         processor_out_streams = out;
1948                 }
1949         }
1950
1951         lr.release ();
1952         lm->acquire ();
1953
1954
1955         if (_meter) {
1956                 _meter->set_max_channels (processor_max_streams);
1957         }
1958
1959         /* make sure we have sufficient scratch buffers to cope with the new processor
1960            configuration
1961         */
1962         _session.ensure_buffers (n_process_buffers ());
1963
1964         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configuration complete\n", _name));
1965
1966         _in_configure_processors = false;
1967         return 0;
1968 }
1969
1970 /** Set all visible processors to a given active state (except Fader, whose state is not changed)
1971  *  @param state New active state for those processors.
1972  */
1973 void
1974 Route::all_visible_processors_active (bool state)
1975 {
1976         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1977
1978         if (_processors.empty()) {
1979                 return;
1980         }
1981
1982         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1983                 if (!(*i)->display_to_user() || boost::dynamic_pointer_cast<Amp> (*i)) {
1984                         continue;
1985                 }
1986 #ifdef MIXBUS
1987                 boost::shared_ptr<PluginInsert> pi;
1988                 if (0 != (pi = boost::dynamic_pointer_cast<PluginInsert>(*i))) {
1989                         if (pi->is_channelstrip ()) {
1990                                 continue;
1991                         }
1992                 }
1993 #endif
1994                 (*i)->enable (state);
1995         }
1996
1997         _session.set_dirty ();
1998 }
1999
2000 bool
2001 Route::processors_reorder_needs_configure (const ProcessorList& new_order)
2002 {
2003         /* check if re-order requires re-configuration of any processors
2004          * -> compare channel configuration for all processors
2005          */
2006         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2007         ChanCount c = input_streams ();
2008
2009         for (ProcessorList::const_iterator j = new_order.begin(); j != new_order.end(); ++j) {
2010                 bool found = false;
2011                 if (c != (*j)->input_streams()) {
2012                         return true;
2013                 }
2014                 for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2015                         if (*i == *j) {
2016                                 found = true;
2017                                 if ((*i)->input_streams() != c) {
2018                                         return true;
2019                                 }
2020                                 c = (*i)->output_streams();
2021                                 break;
2022                         }
2023                 }
2024                 if (!found) {
2025                         return true;
2026                 }
2027         }
2028         return false;
2029 }
2030
2031 #ifdef __clang__
2032 __attribute__((annotate("realtime")))
2033 #endif
2034 void
2035 Route::apply_processor_order (const ProcessorList& new_order)
2036 {
2037         /* need to hold processor_lock; either read or write lock
2038          * and the engine process_lock.
2039          * Due to r/w lock ambiguity we can only assert the latter
2040          */
2041         assert (!AudioEngine::instance()->process_lock().trylock());
2042
2043
2044         /* "new_order" is an ordered list of processors to be positioned according to "placement".
2045          * NOTE: all processors in "new_order" MUST be marked as display_to_user(). There maybe additional
2046          * processors in the current actual processor list that are hidden. Any visible processors
2047          *  in the current list but not in "new_order" will be assumed to be deleted.
2048          */
2049
2050         /* "as_it_will_be" and "_processors" are lists of shared pointers.
2051          * actual memory usage is small, but insert/erase is not actually rt-safe :(
2052          * (note though that  ::processors_reorder_needs_configure() ensured that
2053          * this function will only ever be called from the rt-thread if no processor were removed)
2054          *
2055          * either way, I can't proove it, but an x-run due to re-order here is less likley
2056          * than an x-run-less 'ardour-silent cycle' both of which effectively "click".
2057          */
2058
2059         ProcessorList as_it_will_be;
2060         ProcessorList::iterator oiter;
2061         ProcessorList::const_iterator niter;
2062
2063         oiter = _processors.begin();
2064         niter = new_order.begin();
2065
2066         while (niter !=  new_order.end()) {
2067
2068                 /* if the next processor in the old list is invisible (i.e. should not be in the new order)
2069                    then append it to the temp list.
2070
2071                    Otherwise, see if the next processor in the old list is in the new list. if not,
2072                    its been deleted. If its there, append it to the temp list.
2073                    */
2074
2075                 if (oiter == _processors.end()) {
2076
2077                         /* no more elements in the old list, so just stick the rest of
2078                            the new order onto the temp list.
2079                            */
2080
2081                         as_it_will_be.insert (as_it_will_be.end(), niter, new_order.end());
2082                         while (niter != new_order.end()) {
2083                                 ++niter;
2084                         }
2085                         break;
2086
2087                 } else {
2088
2089                         if (!(*oiter)->display_to_user()) {
2090
2091                                 as_it_will_be.push_back (*oiter);
2092
2093                         } else {
2094
2095                                 /* visible processor: check that its in the new order */
2096
2097                                 if (find (new_order.begin(), new_order.end(), (*oiter)) == new_order.end()) {
2098                                         /* deleted: do nothing, shared_ptr<> will clean up */
2099                                 } else {
2100                                         /* ignore this one, and add the next item from the new order instead */
2101                                         as_it_will_be.push_back (*niter);
2102                                         ++niter;
2103                                 }
2104                         }
2105
2106                         /* now remove from old order - its taken care of no matter what */
2107                         oiter = _processors.erase (oiter);
2108                 }
2109
2110         }
2111         _processors.insert (oiter, as_it_will_be.begin(), as_it_will_be.end());
2112
2113         /* If the meter is in a custom position, find it and make a rough note of its position */
2114         maybe_note_meter_position ();
2115 }
2116
2117 void
2118 Route::move_instrument_down (bool postfader)
2119 {
2120         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2121         ProcessorList new_order;
2122         boost::shared_ptr<Processor> instrument;
2123         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2124                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*i);
2125                 if (pi && pi->plugin ()->get_info ()->is_instrument ()) {
2126                         instrument = *i;
2127                 } else if (instrument && *i == _amp) {
2128                         if (postfader) {
2129                                 new_order.push_back (*i);
2130                                 new_order.push_back (instrument);
2131                         } else {
2132                                 new_order.push_back (instrument);
2133                                 new_order.push_back (*i);
2134                         }
2135                 } else {
2136                         new_order.push_back (*i);
2137                 }
2138         }
2139         if (!instrument) {
2140                 return;
2141         }
2142         lm.release ();
2143         reorder_processors (new_order, 0);
2144 }
2145
2146 int
2147 Route::reorder_processors (const ProcessorList& new_order, ProcessorStreams* err)
2148 {
2149         // it a change is already queued, wait for it
2150         // (unless engine is stopped. apply immediately and proceed
2151         while (g_atomic_int_get (&_pending_process_reorder)) {
2152                 if (!AudioEngine::instance()->running()) {
2153                         DEBUG_TRACE (DEBUG::Processors, "offline apply queued processor re-order.\n");
2154                         Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2155
2156                         apply_processor_order(_pending_processor_order);
2157                         setup_invisible_processors ();
2158
2159                         g_atomic_int_set (&_pending_process_reorder, 0);
2160
2161                         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2162                         set_processor_positions ();
2163                 } else {
2164                         // TODO rather use a semaphore or something.
2165                         // but since ::reorder_processors() is called
2166                         // from the GUI thread, this is fine..
2167                         Glib::usleep(500);
2168                 }
2169         }
2170
2171         if (processors_reorder_needs_configure (new_order) || !AudioEngine::instance()->running()) {
2172
2173                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
2174                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2175                 ProcessorState pstate (this);
2176
2177                 apply_processor_order (new_order);
2178
2179                 if (configure_processors_unlocked (err, &lm)) {
2180                         pstate.restore ();
2181                         return -1;
2182                 }
2183
2184                 lm.release();
2185                 lx.release();
2186
2187                 processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2188                 set_processor_positions ();
2189
2190         } else {
2191                 DEBUG_TRACE (DEBUG::Processors, "Queue clickless processor re-order.\n");
2192                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2193
2194                 // _pending_processor_order is protected by _processor_lock
2195                 _pending_processor_order = new_order;
2196                 g_atomic_int_set (&_pending_process_reorder, 1);
2197         }
2198
2199         /* update processor input/output latency
2200          * (total signal_latency does not change)
2201          */
2202         update_signal_latency (true);
2203
2204         return 0;
2205 }
2206
2207 bool
2208 Route::add_remove_sidechain (boost::shared_ptr<Processor> proc, bool add)
2209 {
2210         if (_session.actively_recording ()) {
2211                 return false;
2212         }
2213
2214         boost::shared_ptr<PluginInsert> pi;
2215         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(proc)) == 0) {
2216                 return false;
2217         }
2218
2219         if (pi->has_sidechain () == add) {
2220                 return true; // ?? call failed, but result is as expected.
2221         }
2222
2223         {
2224                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2225                 ProcessorList::iterator i = find (_processors.begin(), _processors.end(), proc);
2226                 if (i == _processors.end ()) {
2227                         return false;
2228                 }
2229         }
2230
2231         {
2232                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ()); // take before Writerlock to avoid deadlock
2233                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2234                 PBD::Unwinder<bool> uw (_in_sidechain_setup, true);
2235
2236                 lx.release (); // IO::add_port() and ~IO takes process lock  - XXX check if this is safe
2237                 if (add) {
2238                         if (!pi->add_sidechain ()) {
2239                                 return false;
2240                         }
2241                 } else {
2242                         if (!pi->del_sidechain ()) {
2243                                 return false;
2244                         }
2245                 }
2246
2247                 lx.acquire ();
2248                 list<pair<ChanCount, ChanCount> > c = try_configure_processors_unlocked (n_inputs (), 0);
2249                 lx.release ();
2250
2251                 if (c.empty()) {
2252                         if (add) {
2253                                 pi->del_sidechain ();
2254                         } else {
2255                                 pi->add_sidechain ();
2256                                 // TODO restore side-chain's state.
2257                         }
2258                         return false;
2259                 }
2260                 lx.acquire ();
2261                 configure_processors_unlocked (0, &lm);
2262         }
2263
2264         if (pi->has_sidechain ()) {
2265                 pi->sidechain_input ()->changed.connect_same_thread (*this, boost::bind (&Route::sidechain_change_handler, this, _1, _2));
2266         }
2267
2268         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2269         _session.set_dirty ();
2270         return true;
2271 }
2272
2273 bool
2274 Route::plugin_preset_output (boost::shared_ptr<Processor> proc, ChanCount outs)
2275 {
2276         if (_session.actively_recording ()) {
2277                 return false;
2278         }
2279
2280         boost::shared_ptr<PluginInsert> pi;
2281         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(proc)) == 0) {
2282                 return false;
2283         }
2284
2285         {
2286                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2287                 ProcessorList::iterator i = find (_processors.begin(), _processors.end(), proc);
2288                 if (i == _processors.end ()) {
2289                         return false;
2290                 }
2291         }
2292
2293         {
2294                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
2295                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2296
2297                 const ChanCount& old (pi->preset_out ());
2298                 if (!pi->set_preset_out (outs)) {
2299                         return true; // no change, OK
2300                 }
2301
2302                 list<pair<ChanCount, ChanCount> > c = try_configure_processors_unlocked (n_inputs (), 0);
2303                 if (c.empty()) {
2304                         /* not possible */
2305                         pi->set_preset_out (old);
2306                         return false;
2307                 }
2308                 configure_processors_unlocked (0, &lm);
2309         }
2310
2311         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2312         _session.set_dirty ();
2313         return true;
2314 }
2315
2316 bool
2317 Route::reset_plugin_insert (boost::shared_ptr<Processor> proc)
2318 {
2319         ChanCount unused;
2320         return customize_plugin_insert (proc, 0, unused, unused);
2321 }
2322
2323 bool
2324 Route::customize_plugin_insert (boost::shared_ptr<Processor> proc, uint32_t count, ChanCount outs, ChanCount sinks)
2325 {
2326         if (_session.actively_recording ()) {
2327                 return false;
2328         }
2329         boost::shared_ptr<PluginInsert> pi;
2330         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(proc)) == 0) {
2331                 return false;
2332         }
2333
2334         {
2335                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2336                 ProcessorList::iterator i = find (_processors.begin(), _processors.end(), proc);
2337                 if (i == _processors.end ()) {
2338                         return false;
2339                 }
2340         }
2341
2342         {
2343                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
2344                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2345
2346                 bool      old_cust  = pi->custom_cfg ();
2347                 uint32_t  old_cnt   = pi->get_count ();
2348                 ChanCount old_chan  = pi->output_streams ();
2349                 ChanCount old_sinks = pi->natural_input_streams ();
2350
2351                 if (count == 0) {
2352                         pi->set_custom_cfg (false);
2353                 } else {
2354                         pi->set_custom_cfg (true);
2355                         pi->set_count (count);
2356                         pi->set_outputs (outs);
2357                         pi->set_sinks (sinks);
2358                 }
2359
2360                 list<pair<ChanCount, ChanCount> > c = try_configure_processors_unlocked (n_inputs (), 0);
2361                 if (c.empty()) {
2362                         /* not possible */
2363
2364                         pi->set_count (old_cnt);
2365                         pi->set_sinks (old_sinks);
2366                         pi->set_outputs (old_chan);
2367                         pi->set_custom_cfg (old_cust);
2368
2369                         return false;
2370                 }
2371                 configure_processors_unlocked (0, &lm);
2372         }
2373
2374         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2375         _session.set_dirty ();
2376         return true;
2377 }
2378
2379 bool
2380 Route::set_strict_io (const bool enable)
2381 {
2382         Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
2383
2384         if (_strict_io != enable) {
2385                 _strict_io = enable;
2386                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2387                 for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p) {
2388                         boost::shared_ptr<PluginInsert> pi;
2389                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*p)) != 0) {
2390                                 pi->set_strict_io (_strict_io);
2391                         }
2392                 }
2393
2394                 list<pair<ChanCount, ChanCount> > c = try_configure_processors_unlocked (n_inputs (), 0);
2395
2396                 if (c.empty()) {
2397                         // not possible
2398                         _strict_io = !enable; // restore old value
2399                         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p) {
2400                                 boost::shared_ptr<PluginInsert> pi;
2401                                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*p)) != 0) {
2402                                         pi->set_strict_io (_strict_io);
2403                                 }
2404                         }
2405                         return false;
2406                 }
2407                 lm.release ();
2408
2409                 configure_processors (0);
2410                 lx.release ();
2411
2412                 processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2413                 _session.set_dirty ();
2414         }
2415         return true;
2416 }
2417
2418 XMLNode&
2419 Route::get_state()
2420 {
2421         return state (false);
2422 }
2423
2424 XMLNode&
2425 Route::get_template()
2426 {
2427         return state (true);
2428 }
2429
2430 XMLNode&
2431 Route::state (bool save_template)
2432 {
2433         if (!_session._template_state_dir.empty()) {
2434                 foreach_processor (sigc::bind (sigc::mem_fun (*this, &Route::set_plugin_state_dir), _session._template_state_dir));
2435         }
2436
2437         XMLNode *node = new XMLNode("Route");
2438         ProcessorList::iterator i;
2439
2440         if(save_template) {
2441                 XMLNode* child = node->add_child("ProgramVersion");
2442                 child->set_property("created-with", _session.created_with);
2443
2444                 std::string modified_with = string_compose ("%1 %2", PROGRAM_NAME, revision);
2445                 child->set_property("modified-with", modified_with);
2446         }
2447
2448         node->set_property (X_("id"), id ());
2449         node->set_property (X_("name"), name());
2450         node->set_property (X_("default-type"), _default_type);
2451         node->set_property (X_("strict-io"), _strict_io);
2452
2453         node->add_child_nocopy (_presentation_info.get_state());
2454
2455         node->set_property (X_("active"), _active);
2456         node->set_property (X_("denormal-protection"), _denormal_protection);
2457         node->set_property (X_("meter-point"), _meter_point);
2458         node->set_property (X_("disk-io-point"), _disk_io_point);
2459
2460         node->set_property (X_("meter-type"), _meter_type);
2461
2462         if (_route_group) {
2463                 node->set_property (X_("route-group"), _route_group->name());
2464         }
2465
2466         node->add_child_nocopy (_solo_control->get_state ());
2467         node->add_child_nocopy (_solo_isolate_control->get_state ());
2468         node->add_child_nocopy (_solo_safe_control->get_state ());
2469
2470         node->add_child_nocopy (_input->get_state ());
2471         node->add_child_nocopy (_output->get_state ());
2472         node->add_child_nocopy (_mute_master->get_state ());
2473
2474         node->add_child_nocopy (_mute_control->get_state ());
2475         node->add_child_nocopy (_phase_control->get_state ());
2476
2477         if (!skip_saving_automation) {
2478                 node->add_child_nocopy (Automatable::get_automation_xml_state ());
2479         }
2480
2481         if (_comment.length()) {
2482                 XMLNode *cmt = node->add_child ("Comment");
2483                 cmt->add_content (_comment);
2484         }
2485
2486         if (_pannable) {
2487                 node->add_child_nocopy (_pannable->get_state ());
2488         }
2489
2490         {
2491                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2492                 for (i = _processors.begin(); i != _processors.end(); ++i) {
2493                         if (*i == _delayline) {
2494                                 continue;
2495                         }
2496                         if (save_template) {
2497                                 /* template save: do not include internal sends functioning as
2498                                          aux sends because the chance of the target ID
2499                                          in the session where this template is used
2500                                          is not very likely.
2501
2502                                          similarly, do not save listen sends which connect to
2503                                          the monitor section, because these will always be
2504                                          added if necessary.
2505                                          */
2506                                 boost::shared_ptr<InternalSend> is;
2507
2508                                 if ((is = boost::dynamic_pointer_cast<InternalSend> (*i)) != 0) {
2509                                         if (is->role() == Delivery::Listen) {
2510                                                 continue;
2511                                         }
2512                                 }
2513                         }
2514                         node->add_child_nocopy((*i)->get_state ());
2515                 }
2516         }
2517
2518         if (_extra_xml) {
2519                 node->add_child_copy (*_extra_xml);
2520         }
2521
2522         if (_custom_meter_position_noted) {
2523                 boost::shared_ptr<Processor> after = _processor_after_last_custom_meter.lock ();
2524                 if (after) {
2525                         node->set_property (X_("processor-after-last-custom-meter"), after->id());
2526                 }
2527         }
2528
2529         if (!_session._template_state_dir.empty()) {
2530                 foreach_processor (sigc::bind (sigc::mem_fun (*this, &Route::set_plugin_state_dir), ""));
2531         }
2532
2533         node->add_child_copy (Slavable::get_state());
2534
2535         return *node;
2536 }
2537
2538 int
2539 Route::set_state (const XMLNode& node, int version)
2540 {
2541         if (version < 3000) {
2542                 return set_state_2X (node, version);
2543         }
2544
2545         XMLNodeList nlist;
2546         XMLNodeConstIterator niter;
2547         XMLNode *child;
2548
2549         if (node.name() != "Route"){
2550                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
2551                 return -1;
2552         }
2553
2554         std::string route_name;
2555         if (node.get_property (X_("name"), route_name)) {
2556                 Route::set_name (route_name);
2557         }
2558
2559         set_id (node);
2560         _initial_io_setup = true;
2561
2562         Stripable::set_state (node, version);
2563
2564         node.get_property (X_("strict-io"), _strict_io);
2565
2566         if (is_monitor()) {
2567                 /* monitor bus does not get a panner, but if (re)created
2568                    via XML, it will already have one by the time we
2569                    call ::set_state(). so ... remove it.
2570                 */
2571                 unpan ();
2572         }
2573
2574         /* add all processors (except amp, which is always present) */
2575
2576         nlist = node.children();
2577         XMLNode processor_state (X_("processor_state"));
2578
2579         Stateful::save_extra_xml (node);
2580
2581         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2582
2583                 child = *niter;
2584
2585                 if (child->name() == IO::state_node_name) {
2586                         std::string direction;
2587                         if (!child->get_property (X_("direction"), direction)) {
2588                                 continue;
2589                         }
2590
2591                         if (direction == "Input") {
2592                                 _input->set_state (*child, version);
2593                         } else if (direction == "Output") {
2594                                 _output->set_state (*child, version);
2595                         }
2596
2597                 } else if (child->name() == X_("Processor")) {
2598                         processor_state.add_child_copy (*child);
2599                 } else if (child->name() == X_("Pannable")) {
2600                         if (_pannable) {
2601                                 _pannable->set_state (*child, version);
2602                         } else {
2603                                 warning << string_compose (_("Pannable state found for route (%1) without a panner!"), name()) << endmsg;
2604                         }
2605                 } else if (child->name() == Slavable::xml_node_name) {
2606                         Slavable::set_state (*child, version);
2607                 }
2608         }
2609
2610         MeterPoint mp;
2611         if (node.get_property (X_("meter-point"), mp)) {
2612                 set_meter_point (mp, true);
2613                 if (_meter) {
2614                         _meter->set_display_to_user (_meter_point == MeterCustom);
2615                 }
2616         }
2617
2618         DiskIOPoint diop;
2619         if (node.get_property (X_("disk-io-point"), diop)) {
2620                 if (_disk_writer) {
2621                         _disk_writer->set_display_to_user (diop == DiskIOCustom);
2622                 }
2623                 if (_disk_reader) {
2624                         _disk_reader->set_display_to_user (diop == DiskIOCustom);
2625                 }
2626                 set_disk_io_point (diop);
2627         }
2628
2629         node.get_property (X_("meter-type"), _meter_type);
2630
2631         _initial_io_setup = false;
2632
2633         set_processor_state (processor_state);
2634
2635         // this looks up the internal instrument in processors
2636         reset_instrument_info();
2637
2638         bool denormal_protection;
2639         if (node.get_property (X_("denormal-protection"), denormal_protection)) {
2640                 set_denormal_protection (denormal_protection);
2641         }
2642
2643         /* convert old 3001 state */
2644         std::string phase_invert_str;
2645         if (node.get_property (X_("phase-invert"), phase_invert_str)) {
2646                 _phase_control->set_phase_invert (boost::dynamic_bitset<> (phase_invert_str));
2647         }
2648
2649         bool is_active;
2650         if (node.get_property (X_("active"), is_active)) {
2651                 set_active (is_active, this);
2652         }
2653
2654         std::string id_string;
2655         if (node.get_property (X_("processor-after-last-custom-meter"), id_string)) {
2656                 PBD::ID id (id_string);
2657                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2658                 ProcessorList::const_iterator i = _processors.begin ();
2659                 while (i != _processors.end() && (*i)->id() != id) {
2660                         ++i;
2661                 }
2662
2663                 if (i != _processors.end ()) {
2664                         _processor_after_last_custom_meter = *i;
2665                         _custom_meter_position_noted = true;
2666                 }
2667         }
2668
2669         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2670                 child = *niter;
2671
2672                 if (child->name() == X_("Comment")) {
2673
2674                         /* XXX this is a terrible API design in libxml++ */
2675
2676                         XMLNode *cmt = *(child->children().begin());
2677                         _comment = cmt->content();
2678
2679                 }  else if (child->name() == Controllable::xml_node_name) {
2680                         std::string control_name;
2681                         if (!child->get_property (X_("name"), control_name)) {
2682                                 continue;
2683                         }
2684
2685                         if (control_name == _solo_control->name()) {
2686                                 _solo_control->set_state (*child, version);
2687                         } else if (control_name == _solo_safe_control->name()) {
2688                                 _solo_safe_control->set_state (*child, version);
2689                         } else if (control_name == _solo_isolate_control->name()) {
2690                                 _solo_isolate_control->set_state (*child, version);
2691                         } else if (control_name == _mute_control->name()) {
2692                                 _mute_control->set_state (*child, version);
2693                         } else if (control_name == _phase_control->name()) {
2694                                 _phase_control->set_state (*child, version);
2695                         } else {
2696                                 Evoral::Parameter p = EventTypeMap::instance().from_symbol (control_name);
2697                                 if (p.type () >= MidiCCAutomation && p.type () < MidiSystemExclusiveAutomation) {
2698                                         boost::shared_ptr<AutomationControl> ac = automation_control (p, true);
2699                                         if (ac) {
2700                                                 ac->set_state (*child, version);
2701                                         }
2702                                 }
2703                         }
2704                 } else if (child->name() == MuteMaster::xml_node_name) {
2705                         _mute_master->set_state (*child, version);
2706
2707                 } else if (child->name() == Automatable::xml_node_name) {
2708                         set_automation_xml_state (*child, Evoral::Parameter(NullAutomation));
2709                 }
2710         }
2711
2712         if (_delayline) {
2713                 _delayline->set_name (name ());
2714         }
2715
2716         return 0;
2717 }
2718
2719 int
2720 Route::set_state_2X (const XMLNode& node, int version)
2721 {
2722         LocaleGuard lg;
2723         XMLNodeList nlist;
2724         XMLNodeConstIterator niter;
2725         XMLNode *child;
2726         XMLProperty const * prop;
2727
2728         /* 2X things which still remain to be handled:
2729          * default-type
2730          * automation
2731          * controlouts
2732          */
2733
2734         if (node.name() != "Route") {
2735                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
2736                 return -1;
2737         }
2738
2739         Stripable::set_state (node, version);
2740
2741         if ((prop = node.property (X_("denormal-protection"))) != 0) {
2742                 set_denormal_protection (string_to<bool> (prop->value()));
2743         }
2744
2745         if ((prop = node.property (X_("muted"))) != 0) {
2746
2747                 bool first = true;
2748                 bool muted = string_to<bool> (prop->value());
2749
2750                 if (muted) {
2751
2752                         string mute_point;
2753
2754                         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
2755
2756                                 if (string_to<bool> (prop->value())){
2757                                         mute_point = mute_point + "PreFader";
2758                                         first = false;
2759                                 }
2760                         }
2761
2762                         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
2763
2764                                 if (string_to<bool> (prop->value())){
2765
2766                                         if (!first) {
2767                                                 mute_point = mute_point + ",";
2768                                         }
2769
2770                                         mute_point = mute_point + "PostFader";
2771                                         first = false;
2772                                 }
2773                         }
2774
2775                         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
2776
2777                                 if (string_to<bool> (prop->value())){
2778
2779                                         if (!first) {
2780                                                 mute_point = mute_point + ",";
2781                                         }
2782
2783                                         mute_point = mute_point + "Listen";
2784                                         first = false;
2785                                 }
2786                         }
2787
2788                         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
2789
2790                                 if (string_to<bool> (prop->value())){
2791
2792                                         if (!first) {
2793                                                 mute_point = mute_point + ",";
2794                                         }
2795
2796                                         mute_point = mute_point + "Main";
2797                                 }
2798                         }
2799
2800                         _mute_master->set_mute_points (mute_point);
2801                         _mute_master->set_muted_by_self (true);
2802                 }
2803         }
2804
2805         if ((prop = node.property (X_("meter-point"))) != 0) {
2806                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
2807         }
2808
2809         /* IOs */
2810
2811         nlist = node.children ();
2812         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2813
2814                 child = *niter;
2815
2816                 if (child->name() == IO::state_node_name) {
2817
2818                         /* there is a note in IO::set_state_2X() about why we have to call
2819                            this directly.
2820                            */
2821
2822                         _input->set_state_2X (*child, version, true);
2823                         _output->set_state_2X (*child, version, false);
2824
2825                         if ((prop = child->property (X_("name"))) != 0) {
2826                                 Route::set_name (prop->value ());
2827                         }
2828
2829                         set_id (*child);
2830
2831                         if ((prop = child->property (X_("active"))) != 0) {
2832                                 bool yn = string_to<bool> (prop->value());
2833                                 _active = !yn; // force switch
2834                                 set_active (yn, this);
2835                         }
2836
2837                         if ((prop = child->property (X_("gain"))) != 0) {
2838                                 gain_t val;
2839
2840                                 if (sscanf (prop->value().c_str(), "%f", &val) == 1) {
2841                                         _amp->gain_control()->set_value (val, Controllable::NoGroup);
2842                                 }
2843                         }
2844
2845                         /* Set up Panners in the IO */
2846                         XMLNodeList io_nlist = child->children ();
2847
2848                         XMLNodeConstIterator io_niter;
2849                         XMLNode *io_child;
2850
2851                         for (io_niter = io_nlist.begin(); io_niter != io_nlist.end(); ++io_niter) {
2852
2853                                 io_child = *io_niter;
2854
2855                                 if (io_child->name() == X_("Panner")) {
2856                                         _main_outs->panner_shell()->set_state(*io_child, version);
2857                                 } else if (io_child->name() == X_("Automation")) {
2858                                         /* IO's automation is for the fader */
2859                                         _amp->set_automation_xml_state (*io_child, Evoral::Parameter (GainAutomation));
2860                                 }
2861                         }
2862                 }
2863         }
2864
2865         XMLNodeList redirect_nodes;
2866
2867         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2868
2869                 child = *niter;
2870
2871                 if (child->name() == X_("Send") || child->name() == X_("Insert")) {
2872                         redirect_nodes.push_back(child);
2873                 }
2874
2875         }
2876
2877         set_processor_state_2X (redirect_nodes, version);
2878
2879         Stateful::save_extra_xml (node);
2880
2881         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2882                 child = *niter;
2883
2884                 if (child->name() == X_("Comment")) {
2885
2886                         /* XXX this is a terrible API design in libxml++ */
2887
2888                         XMLNode *cmt = *(child->children().begin());
2889                         _comment = cmt->content();
2890
2891                 } else if (child->name() == Controllable::xml_node_name && (prop = child->property("name")) != 0) {
2892                         if (prop->value() == X_("solo")) {
2893                                 _solo_control->set_state (*child, version);
2894                         } else if (prop->value() == X_("mute")) {
2895                                 _mute_control->set_state (*child, version);
2896                         }
2897
2898                 }
2899         }
2900
2901         return 0;
2902 }
2903
2904 XMLNode&
2905 Route::get_processor_state ()
2906 {
2907         XMLNode* root = new XMLNode (X_("redirects"));
2908         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2909                 root->add_child_nocopy ((*i)->get_state ());
2910         }
2911
2912         return *root;
2913 }
2914
2915 void
2916 Route::set_processor_state_2X (XMLNodeList const & nList, int version)
2917 {
2918         /* We don't bother removing existing processors not in nList, as this
2919            method will only be called when creating a Route from scratch, not
2920            for undo purposes.  Just put processors in at the appropriate place
2921            in the list.
2922         */
2923
2924         for (XMLNodeConstIterator i = nList.begin(); i != nList.end(); ++i) {
2925                 add_processor_from_xml_2X (**i, version);
2926         }
2927 }
2928
2929 void
2930 Route::set_processor_state (const XMLNode& node)
2931 {
2932         const XMLNodeList &nlist = node.children();
2933         XMLNodeConstIterator niter;
2934         ProcessorList new_order;
2935         bool must_configure = false;
2936
2937         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2938
2939                 XMLProperty* prop = (*niter)->property ("type");
2940
2941                 if (prop->value() == "amp") {
2942                         _amp->set_state (**niter, Stateful::current_state_version);
2943                         new_order.push_back (_amp);
2944                 } else if (prop->value() == "trim") {
2945                         _trim->set_state (**niter, Stateful::current_state_version);
2946                         new_order.push_back (_trim);
2947                 } else if (prop->value() == "meter") {
2948                         _meter->set_state (**niter, Stateful::current_state_version);
2949                         new_order.push_back (_meter);
2950                 } else if (prop->value() == "polarity") {
2951                         _polarity->set_state (**niter, Stateful::current_state_version);
2952                         new_order.push_back (_polarity);
2953                 } else if (prop->value() == "delay") {
2954                         // skip -- internal
2955                 } else if (prop->value() == "main-outs") {
2956                         _main_outs->set_state (**niter, Stateful::current_state_version);
2957                 } else if (prop->value() == "intreturn") {
2958                         if (!_intreturn) {
2959                                 _intreturn.reset (new InternalReturn (_session));
2960                                 must_configure = true;
2961                         }
2962                         _intreturn->set_state (**niter, Stateful::current_state_version);
2963                 } else if (is_monitor() && prop->value() == "monitor") {
2964                         if (!_monitor_control) {
2965                                 _monitor_control.reset (new MonitorProcessor (_session));
2966                                 must_configure = true;
2967                         }
2968                         _monitor_control->set_state (**niter, Stateful::current_state_version);
2969                 } else if (prop->value() == "capture") {
2970                         /* CapturingProcessor should never be restored, it's always
2971                            added explicitly when needed */
2972                 } else if (prop->value() == "diskreader" && _disk_reader) {
2973                         _disk_reader->set_state (**niter, Stateful::current_state_version);
2974                         new_order.push_back (_disk_reader);
2975                 } else if (prop->value() == "diskwriter" && _disk_writer) {
2976                         _disk_writer->set_state (**niter, Stateful::current_state_version);
2977                         new_order.push_back (_disk_writer);
2978                 } else {
2979                         set_processor_state (**niter, prop, new_order, must_configure);
2980                 }
2981         }
2982
2983         ProcessorList old_list = _processors; // keep a copy
2984         {
2985                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
2986                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2987                 /* re-assign _processors w/o process-lock.
2988                  * if there's an IO-processor present in _processors but
2989                  * not in new_order, it will be deleted and ~IO takes
2990                  * a process lock.
2991                  */
2992                 _processors = new_order;
2993
2994                 /* When a required/existing internal processor is not in the list, it needs to
2995                  * be added via configure_processors() -> setup_invisible_processors()
2996                  */
2997                 if (_monitor_control) {
2998                         must_configure |= find (_processors.begin(), _processors.end(), _monitor_control) == _processors.end ();
2999                 }
3000                 if (_main_outs) {
3001                         must_configure |= find (_processors.begin(), _processors.end(), _main_outs) == _processors.end ();
3002                 }
3003                 if (_delayline) {
3004                         must_configure |= find (_processors.begin(), _processors.end(), _delayline) == _processors.end ();
3005                 }
3006                 if (_intreturn) {
3007                         must_configure |= find (_processors.begin(), _processors.end(), _intreturn) == _processors.end ();
3008                 }
3009
3010                 if (must_configure && !_session.loading()) {
3011                         configure_processors_unlocked (0, &lm);
3012                 }
3013
3014                 for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3015
3016                         (*i)->set_owner (this);
3017                         (*i)->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false));
3018
3019                         boost::shared_ptr<PluginInsert> pi;
3020
3021                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
3022                                 if (pi->has_no_inputs ()) {
3023                                         _have_internal_generator = true;
3024                                         break;
3025                                 }
3026                         }
3027                 }
3028         }
3029         /* drop references w/o process-lock (I/O procs may re-take it in ~IO() */
3030         old_list.clear ();
3031
3032         reset_instrument_info ();
3033         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
3034         set_processor_positions ();
3035 }
3036
3037 bool
3038 Route::set_processor_state (XMLNode const & node, XMLProperty const* prop, ProcessorList& new_order, bool& must_configure)
3039 {
3040         ProcessorList::iterator o;
3041
3042         for (o = _processors.begin(); o != _processors.end(); ++o) {
3043                 XMLProperty const * id_prop = node.property(X_("id"));
3044                 if (id_prop && (*o)->id() == id_prop->value()) {
3045                         (*o)->set_state (node, Stateful::current_state_version);
3046                         new_order.push_back (*o);
3047                         break;
3048                 }
3049         }
3050
3051         // If the processor (node) is not on the route then create it
3052
3053         if (o == _processors.end()) {
3054
3055                 boost::shared_ptr<Processor> processor;
3056
3057                 if (prop->value() == "intsend") {
3058
3059                         processor.reset (new InternalSend (_session, _pannable, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), boost::shared_ptr<Route>(), Delivery::Aux, true));
3060
3061                 } else if (prop->value() == "ladspa" || prop->value() == "Ladspa" ||
3062                            prop->value() == "lv2" ||
3063                            prop->value() == "windows-vst" ||
3064                            prop->value() == "mac-vst" ||
3065                            prop->value() == "lxvst" ||
3066                            prop->value() == "luaproc" ||
3067                            prop->value() == "audiounit") {
3068
3069                         if (_session.get_disable_all_loaded_plugins ()) {
3070                                 processor.reset (new UnknownProcessor (_session, node));
3071                         } else {
3072                                 processor.reset (new PluginInsert (_session));
3073                                 processor->set_owner (this);
3074                                 if (_strict_io) {
3075                                         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(processor);
3076                                         pi->set_strict_io (true);
3077                                 }
3078
3079                         }
3080                 } else if (prop->value() == "port") {
3081
3082                         processor.reset (new PortInsert (_session, _pannable, _mute_master));
3083
3084                 } else if (prop->value() == "send") {
3085
3086                         processor.reset (new Send (_session, _pannable, _mute_master, Delivery::Send, true));
3087                         boost::shared_ptr<Send> send = boost::dynamic_pointer_cast<Send> (processor);
3088                         send->SelfDestruct.connect_same_thread (*this,
3089                                                                 boost::bind (&Route::processor_selfdestruct, this, boost::weak_ptr<Processor> (processor)));
3090
3091                 } else {
3092                         warning << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
3093                         return false;
3094                 }
3095
3096                 if (processor->set_state (node, Stateful::current_state_version) != 0) {
3097                         /* This processor could not be configured.  Turn it into a UnknownProcessor */
3098                         processor.reset (new UnknownProcessor (_session, node));
3099                 }
3100
3101                 /* subscribe to Sidechain IO changes */
3102                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (processor);
3103                 if (pi && pi->has_sidechain ()) {
3104                         pi->sidechain_input ()->changed.connect_same_thread (*this, boost::bind (&Route::sidechain_change_handler, this, _1, _2));
3105                 }
3106
3107                 /* we have to note the monitor send here, otherwise a new one will be created
3108                    and the state of this one will be lost.
3109                 */
3110                 boost::shared_ptr<InternalSend> isend = boost::dynamic_pointer_cast<InternalSend> (processor);
3111                 if (isend && isend->role() == Delivery::Listen) {
3112                         _monitor_send = isend;
3113                 }
3114
3115                 /* it doesn't matter if invisible processors are added here, as they
3116                    will be sorted out by setup_invisible_processors () shortly.
3117                 */
3118
3119                 new_order.push_back (processor);
3120                 must_configure = true;
3121         }
3122         return true;
3123 }
3124
3125 void
3126 Route::silence (samplecnt_t nframes)
3127 {
3128         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
3129         if (!lm.locked()) {
3130                 return;
3131         }
3132
3133         silence_unlocked (nframes);
3134 }
3135
3136 void
3137 Route::silence_unlocked (samplecnt_t nframes)
3138 {
3139         /* Must be called with the processor lock held */
3140
3141         const samplepos_t now = _session.transport_sample ();
3142
3143         _output->silence (nframes);
3144
3145         // update owned automated controllables
3146         automation_run (now, nframes);
3147         if (_pannable) {
3148                 _pannable->automation_run (now, nframes);
3149         }
3150
3151         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3152                 boost::shared_ptr<PluginInsert> pi;
3153
3154                 if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
3155                         /* evaluate automated automation controls */
3156                         pi->automation_run (now, nframes);
3157                         /* skip plugins, they don't need anything when we're not active */
3158                         continue;
3159                 }
3160
3161                 (*i)->silence (nframes, now);
3162         }
3163 }
3164
3165 void
3166 Route::add_internal_return ()
3167 {
3168         if (!_intreturn) {
3169                 _intreturn.reset (new InternalReturn (_session));
3170                 add_processor (_intreturn, PreFader);
3171         }
3172 }
3173
3174 void
3175 Route::add_send_to_internal_return (InternalSend* send)
3176 {
3177         Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3178
3179         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
3180                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
3181
3182                 if (d) {
3183                         return d->add_send (send);
3184                 }
3185         }
3186 }
3187
3188 void
3189 Route::remove_send_from_internal_return (InternalSend* send)
3190 {
3191         Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3192
3193         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
3194                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
3195
3196                 if (d) {
3197                         return d->remove_send (send);
3198                 }
3199         }
3200 }
3201
3202 void
3203 Route::enable_monitor_send ()
3204 {
3205         /* Caller must hold process lock */
3206         assert (!AudioEngine::instance()->process_lock().trylock());
3207
3208         /* master never sends to monitor section via the normal mechanism */
3209         assert (!is_master ());
3210         assert (!is_monitor ());
3211
3212         /* make sure we have one */
3213         if (!_monitor_send) {
3214                 _monitor_send.reset (new InternalSend (_session, _pannable, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), _session.monitor_out(), Delivery::Listen));
3215                 _monitor_send->set_display_to_user (false);
3216         }
3217
3218         /* set it up */
3219         configure_processors (0);
3220 }
3221
3222 /** Add an aux send to a route.
3223  *  @param route route to send to.
3224  *  @param before Processor to insert before, or 0 to insert at the end.
3225  */
3226 int
3227 Route::add_aux_send (boost::shared_ptr<Route> route, boost::shared_ptr<Processor> before)
3228 {
3229         assert (route != _session.monitor_out ());
3230
3231         {
3232                 Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3233
3234                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
3235
3236                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend> (*x);
3237
3238                         if (d && d->target_route() == route) {
3239                                 /* already listening via the specified IO: do nothing */
3240                                 return 0;
3241                         }
3242                 }
3243         }
3244
3245         try {
3246
3247                 boost::shared_ptr<InternalSend> listener;
3248
3249                 {
3250                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3251                         listener.reset (new InternalSend (_session, _pannable, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), route, Delivery::Aux));
3252                 }
3253
3254                 add_processor (listener, before);
3255
3256         } catch (failed_constructor& err) {
3257                 return -1;
3258         }
3259
3260         return 0;
3261 }
3262
3263 int
3264 Route::add_foldback_send (boost::shared_ptr<Route> route)
3265 {
3266         assert (route != _session.monitor_out ());
3267         boost::shared_ptr<Processor> before = before_processor_for_placement (PreFader);
3268
3269         {
3270                 Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3271
3272                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
3273
3274                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend> (*x);
3275
3276                         if (d && d->target_route() == route) {
3277                                 /* already listening via the specified IO: do nothing */
3278                                 return 0;
3279                         }
3280                 }
3281         }
3282
3283         try {
3284
3285                 boost::shared_ptr<InternalSend> listener;
3286
3287                 {
3288                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3289                         listener.reset (new InternalSend (_session, _pannable, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), route, Delivery::Foldback));
3290                 }
3291
3292                 listener->panner_shell()->set_linked_to_route (false);
3293                 listener->panner_shell()->select_panner_by_uri ("http://ardour.org/plugin/panner_balance");
3294                 add_processor (listener, before);
3295
3296         } catch (failed_constructor& err) {
3297                 return -1;
3298         }
3299
3300         return 0;
3301 }
3302
3303 void
3304 Route::remove_aux_or_listen (boost::shared_ptr<Route> route)
3305 {
3306         ProcessorStreams err;
3307         ProcessorList::iterator tmp;
3308
3309         {
3310                 Glib::Threads::RWLock::ReaderLock rl(_processor_lock);
3311
3312                 /* have to do this early because otherwise processor reconfig
3313                  * will put _monitor_send back in the list
3314                  */
3315
3316                 if (route == _session.monitor_out()) {
3317                         _monitor_send.reset ();
3318                 }
3319
3320           again:
3321                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
3322
3323                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
3324
3325                         if (d && d->target_route() == route) {
3326                                 rl.release ();
3327                                 if (remove_processor (*x, &err, false) > 0) {
3328                                         rl.acquire ();
3329                                         continue;
3330                                 }
3331                                 rl.acquire ();
3332
3333                                 /* list could have been demolished while we dropped the lock
3334                                    so start over.
3335                                 */
3336                                 if (_session.engine().running()) {
3337                                         /* i/o processors cannot be removed if the engine is not running
3338                                          * so don't live-loop in case the engine is N/A or dies
3339                                          */
3340                                         goto again;
3341                                 }
3342                         }
3343                 }
3344         }
3345 }
3346
3347 void
3348 Route::set_comment (string cmt, void *src)
3349 {
3350         _comment = cmt;
3351         comment_changed ();
3352         _session.set_dirty ();
3353 }
3354
3355 bool
3356 Route::add_fed_by (boost::shared_ptr<Route> other, bool via_sends_only)
3357 {
3358         FeedRecord fr (other, via_sends_only);
3359
3360         pair<FedBy::iterator,bool> result =  _fed_by.insert (fr);
3361
3362         if (!result.second) {
3363
3364                 /* already a record for "other" - make sure sends-only information is correct */
3365                 if (!via_sends_only && result.first->sends_only) {
3366                         FeedRecord* frp = const_cast<FeedRecord*>(&(*result.first));
3367                         frp->sends_only = false;
3368                 }
3369         }
3370
3371         return result.second;
3372 }
3373
3374 void
3375 Route::clear_fed_by ()
3376 {
3377         _fed_by.clear ();
3378 }
3379
3380 bool
3381 Route::feeds (boost::shared_ptr<Route> other, bool* via_sends_only)
3382 {
3383         const FedBy& fed_by (other->fed_by());
3384
3385         for (FedBy::const_iterator f = fed_by.begin(); f != fed_by.end(); ++f) {
3386                 boost::shared_ptr<Route> sr = f->r.lock();
3387
3388                 if (sr && (sr.get() == this)) {
3389
3390                         if (via_sends_only) {
3391                                 *via_sends_only = f->sends_only;
3392                         }
3393
3394                         return true;
3395                 }
3396         }
3397
3398         return false;
3399 }
3400
3401 IOVector
3402 Route::all_inputs () const
3403 {
3404         /* TODO, if this works as expected,
3405          * cache the IOVector and maintain it via
3406          * input_change_handler(), sidechain_change_handler() etc
3407          */
3408         IOVector ios;
3409         ios.push_back (_input);
3410
3411         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3412         for (ProcessorList::const_iterator r = _processors.begin(); r != _processors.end(); ++r) {
3413
3414                 boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*r);
3415                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*r);
3416                 if (pi != 0) {
3417                         assert (iop == 0);
3418                         iop = pi->sidechain();
3419                 }
3420
3421                 if (iop != 0 && iop->input()) {
3422                         ios.push_back (iop->input());
3423                 }
3424         }
3425         return ios;
3426 }
3427
3428 IOVector
3429 Route::all_outputs () const
3430 {
3431         IOVector ios;
3432         // _output is included via Delivery
3433         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3434         for (ProcessorList::const_iterator r = _processors.begin(); r != _processors.end(); ++r) {
3435                 boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*r);
3436                 if (iop != 0 && iop->output()) {
3437                         ios.push_back (iop->output());
3438                 }
3439         }
3440         return ios;
3441 }
3442
3443 bool
3444 Route::direct_feeds_according_to_reality (boost::shared_ptr<Route> other, bool* via_send_only)
3445 {
3446         DEBUG_TRACE (DEBUG::Graph, string_compose ("Feeds from %1 (-> %2)?\n", _name, other->name()));
3447         if (other->all_inputs().fed_by (_output)) {
3448                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\tdirect FEEDS to %1\n", other->name()));
3449                 if (via_send_only) {
3450                         *via_send_only = false;
3451                 }
3452
3453                 return true;
3454         }
3455
3456         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3457
3458         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); ++r) {
3459
3460                 boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*r);
3461                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*r);
3462                 if (pi != 0) {
3463                         assert (iop == 0);
3464                         iop = pi->sidechain();
3465                 }
3466
3467                 if (iop != 0) {
3468                         boost::shared_ptr<const IO> iop_out = iop->output();
3469                         if (other.get() == this && iop_out && iop->input() && iop_out->connected_to (iop->input())) {
3470                                 // TODO this needs a delaylines in the Insert to align connections (!)
3471                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does feed its own return (%2)\n", iop->name(), other->name()));
3472                                 continue;
3473                         }
3474                         if ((iop_out && other->all_inputs().fed_by (iop_out)) || iop->feeds (other)) {
3475                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does feed %2\n", iop->name(), other->name()));
3476                                 if (via_send_only) {
3477                                         *via_send_only = true;
3478                                 }
3479                                 return true;
3480                         } else {
3481                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does NOT feed %2\n", iop->name(), other->name()));
3482                         }
3483                 }
3484         }
3485
3486         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tdoes NOT feed %1\n", other->name()));
3487         return false;
3488 }
3489
3490 bool
3491 Route::direct_feeds_according_to_graph (boost::shared_ptr<Route> other, bool* via_send_only)
3492 {
3493         return _session._current_route_graph.has (boost::dynamic_pointer_cast<Route> (shared_from_this ()), other, via_send_only);
3494 }
3495
3496 bool
3497 Route::feeds_according_to_graph (boost::shared_ptr<Route> other)
3498 {
3499         return _session._current_route_graph.feeds (boost::dynamic_pointer_cast<Route> (shared_from_this ()), other);
3500 }
3501
3502 /** Called from the (non-realtime) butler thread when the transport is stopped */
3503 void
3504 Route::non_realtime_transport_stop (samplepos_t now, bool flush)
3505 {
3506         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3507
3508         Automatable::non_realtime_transport_stop (now, flush);
3509
3510         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3511
3512                 if (!_have_internal_generator && (Config->get_plugins_stop_with_transport() && flush)) {
3513                         (*i)->flush ();
3514                 }
3515
3516                 (*i)->non_realtime_transport_stop (now, flush);
3517         }
3518 }
3519
3520 void
3521 Route::realtime_handle_transport_stopped ()
3522 {
3523         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3524
3525         /* currently only by Plugin, queue note-off events */
3526         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3527                 (*i)->realtime_handle_transport_stopped ();
3528         }
3529 }
3530
3531
3532 void
3533 Route::input_change_handler (IOChange change, void * /*src*/)
3534 {
3535         if (_session.loading()) {
3536                 return;
3537         }
3538
3539         if ((change.type & IOChange::ConfigurationChanged)) {
3540                 /* This is called with the process lock held if change
3541                    contains ConfigurationChanged
3542                 */
3543                 configure_processors (0);
3544                 io_changed (); /* EMIT SIGNAL */
3545         }
3546
3547         if (_solo_control->soloed_by_others_upstream() || _solo_isolate_control->solo_isolated_by_upstream()) {
3548                 int sbou = 0;
3549                 int ibou = 0;
3550                 boost::shared_ptr<RouteList> routes = _session.get_routes ();
3551                 if (_input->connected()) {
3552                         for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3553                                 if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3554                                         continue;
3555                                 }
3556                                 bool sends_only;
3557                                 bool does_feed = (*i)->direct_feeds_according_to_reality (boost::dynamic_pointer_cast<Route> (shared_from_this()), &sends_only);
3558                                 if (does_feed && !sends_only) {
3559                                         if ((*i)->soloed()) {
3560                                                 ++sbou;
3561                                         }
3562                                         if ((*i)->solo_isolate_control()->solo_isolated()) {
3563                                                 ++ibou;
3564                                         }
3565                                 }
3566                         }
3567                 }
3568
3569                 int delta  = sbou - _solo_control->soloed_by_others_upstream();
3570                 int idelta = ibou - _solo_isolate_control->solo_isolated_by_upstream();
3571
3572                 if (idelta < -1) {
3573                         PBD::warning << string_compose (
3574                                         _("Invalid Solo-Isolate propagation: from:%1 new:%2 - old:%3 = delta:%4"),
3575                                         _name, ibou, _solo_isolate_control->solo_isolated_by_upstream(), idelta)
3576                                      << endmsg;
3577
3578                 }
3579
3580                 if (_solo_control->soloed_by_others_upstream()) {
3581                         // ignore new connections (they're not propagated)
3582                         if (delta <= 0) {
3583                                 _solo_control->mod_solo_by_others_upstream (delta);
3584                         }
3585                 }
3586
3587                 if (_solo_isolate_control->solo_isolated_by_upstream()) {
3588                         // solo-isolate currently only propagates downstream
3589                         if (idelta < 0) {
3590                                 _solo_isolate_control->mod_solo_isolated_by_upstream (1);
3591                         }
3592                         //_solo_isolated_by_upstream = ibou;
3593                 }
3594
3595                 // Session::route_solo_changed  does not propagate indirect solo-changes
3596                 // propagate downstream to tracks
3597                 for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3598                         if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3599                                 continue;
3600                         }
3601                         bool sends_only;
3602                         bool does_feed = feeds (*i, &sends_only);
3603                         if (delta <= 0 && does_feed && !sends_only) {
3604                                 (*i)->solo_control()->mod_solo_by_others_upstream (delta);
3605                         }
3606
3607                         if (idelta < 0 && does_feed && !sends_only) {
3608                                 (*i)->solo_isolate_control()->mod_solo_isolated_by_upstream (-1);
3609                         }
3610                 }
3611         }
3612 }
3613
3614 void
3615 Route::output_change_handler (IOChange change, void * /*src*/)
3616 {
3617         if (_initial_io_setup) {
3618                 return;
3619         }
3620
3621         if ((change.type & IOChange::ConfigurationChanged)) {
3622                 /* This is called with the process lock held if change
3623                    contains ConfigurationChanged
3624                 */
3625                 configure_processors (0);
3626
3627                 if (is_master()) {
3628                         _session.reset_monitor_section();
3629                 }
3630
3631                 io_changed (); /* EMIT SIGNAL */
3632         }
3633
3634         if ((change.type & IOChange::ConnectionsChanged)) {
3635
3636                 /* do this ONLY if connections have changed. Configuration
3637                  * changes do not, by themselves alter solo upstream or
3638                  * downstream status.
3639                  */
3640
3641                 if (_solo_control->soloed_by_others_downstream()) {
3642                         int sbod = 0;
3643                         /* checking all all downstream routes for
3644                          * explicit of implict solo is a rather drastic measure,
3645                          * ideally the input_change_handler() of the other route
3646                          * would propagate the change to us.
3647                          */
3648                         boost::shared_ptr<RouteList> routes = _session.get_routes ();
3649                         if (_output->connected()) {
3650                                 for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3651                                         if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3652                                                 continue;
3653                                         }
3654                                         bool sends_only;
3655                                         bool does_feed = direct_feeds_according_to_reality (*i, &sends_only);
3656                                         if (does_feed && !sends_only) {
3657                                                 if ((*i)->soloed()) {
3658                                                         ++sbod;
3659                                                         break;
3660                                                 }
3661                                         }
3662                                 }
3663                         }
3664
3665                         int delta = sbod - _solo_control->soloed_by_others_downstream();
3666                         if (delta <= 0) {
3667                                 // do not allow new connections to change implicit solo (no propagation)
3668                                 _solo_control->mod_solo_by_others_downstream (delta);
3669                                 // Session::route_solo_changed() does not propagate indirect solo-changes
3670                                 // propagate upstream to tracks
3671                                 boost::shared_ptr<Route> shared_this = boost::dynamic_pointer_cast<Route> (shared_from_this());
3672                                 for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3673                                         if ((*i).get() == this || !can_solo()) {
3674                                                 continue;
3675                                         }
3676                                         bool sends_only;
3677                                         bool does_feed = (*i)->feeds (shared_this, &sends_only);
3678                                         if (delta != 0 && does_feed && !sends_only) {
3679                                                 (*i)->solo_control()->mod_solo_by_others_downstream (delta);
3680                                         }
3681                                 }
3682
3683                         }
3684                 }
3685         }
3686 }
3687
3688 void
3689 Route::sidechain_change_handler (IOChange change, void* src)
3690 {
3691         if (_initial_io_setup || _in_sidechain_setup) {
3692                 return;
3693         }
3694
3695         input_change_handler (change, src);
3696 }
3697
3698 uint32_t
3699 Route::pans_required () const
3700 {
3701         if (n_outputs().n_audio() < 2) {
3702                 return 0;
3703         }
3704
3705         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
3706 }
3707
3708 void
3709 Route::flush_processor_buffers_locked (samplecnt_t nframes)
3710 {
3711         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3712                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery> (*i);
3713                 if (d) {
3714                         d->flush_buffers (nframes);
3715                 } else {
3716                         boost::shared_ptr<PortInsert> p = boost::dynamic_pointer_cast<PortInsert> (*i);
3717                         if (p) {
3718                                 p->flush_buffers (nframes);
3719                         }
3720                 }
3721         }
3722 }
3723
3724 void
3725 Route::flush_processors ()
3726 {
3727         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3728
3729         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3730                 (*i)->flush ();
3731         }
3732 }
3733
3734 samplecnt_t
3735 Route::playback_latency (bool incl_downstream) const
3736 {
3737         samplecnt_t rv;
3738         if (_disk_reader) {
3739                 rv = _disk_reader->output_latency ();
3740         } else {
3741                 rv = _signal_latency;
3742         }
3743         if (incl_downstream) {
3744                 rv += _output->connected_latency (true);
3745         } else {
3746                 rv += _output->latency ();
3747         }
3748         return rv;
3749 }
3750
3751 pframes_t
3752 Route::latency_preroll (pframes_t nframes, samplepos_t& start_sample, samplepos_t& end_sample)
3753 {
3754         samplecnt_t latency_preroll = _session.remaining_latency_preroll ();
3755         if (latency_preroll == 0) {
3756                 return nframes;
3757         }
3758         if (!_disk_reader) {
3759                 start_sample -= latency_preroll;
3760                 end_sample   -= latency_preroll;
3761                 return nframes;
3762         }
3763
3764         if (latency_preroll > playback_latency ()) {
3765                 no_roll_unlocked (nframes, start_sample - latency_preroll, end_sample - latency_preroll, false);
3766                 return 0;
3767         }
3768
3769         start_sample -= latency_preroll;
3770         end_sample -= latency_preroll;
3771         return nframes;
3772 }
3773
3774 int
3775 Route::roll (pframes_t nframes, samplepos_t start_sample, samplepos_t end_sample, bool& need_butler)
3776 {
3777         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
3778
3779         if (!lm.locked()) {
3780                 return 0;
3781         }
3782
3783         if (!_active) {
3784                 silence_unlocked (nframes);
3785                 _meter->reset();
3786                 return 0;
3787         }
3788
3789         if ((nframes = latency_preroll (nframes, start_sample, end_sample)) == 0) {
3790                 return 0;
3791         }
3792
3793         run_route (start_sample, end_sample, nframes, (!_disk_writer || !_disk_writer->record_enabled()) && _session.transport_rolling(), true);
3794
3795         if ((_disk_reader && _disk_reader->need_butler()) || (_disk_writer && _disk_writer->need_butler())) {
3796                 need_butler = true;
3797         }
3798         return 0;
3799 }
3800
3801 int
3802 Route::no_roll (pframes_t nframes, samplepos_t start_sample, samplepos_t end_sample, bool session_state_changing)
3803 {
3804         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
3805
3806         if (!lm.locked()) {
3807                 return 0;
3808         }
3809
3810         return no_roll_unlocked (nframes, start_sample, end_sample, session_state_changing);
3811 }
3812
3813 int
3814 Route::no_roll_unlocked (pframes_t nframes, samplepos_t start_sample, samplepos_t end_sample, bool session_state_changing)
3815 {
3816         /* Must be called with the processor lock held */
3817
3818         if (!_active) {
3819                 silence_unlocked (nframes);
3820                 _meter->reset();
3821                 return 0;
3822         }
3823
3824         if (session_state_changing) {
3825                 if (_session.transport_speed() != 0.0f) {
3826                         /* we're rolling but some state is changing (e.g. our diskstream contents)
3827                            so we cannot use them. Be silent till this is over.
3828
3829                            XXX note the absurdity of ::no_roll() being called when we ARE rolling!
3830                         */
3831                         silence_unlocked (nframes);
3832                         _meter->reset();
3833                         return 0;
3834                 }
3835                 /* we're really not rolling, so we're either delivery silence or actually
3836                    monitoring, both of which are safe to do while session_state_changing is true.
3837                 */
3838         }
3839
3840         run_route (start_sample, end_sample, nframes, false, false);
3841         return 0;
3842 }
3843
3844 int
3845 Route::silent_roll (pframes_t nframes, samplepos_t /*start_sample*/, samplepos_t /*end_sample*/, bool& /* need_butler */)
3846 {
3847         silence (nframes);
3848         flush_processor_buffers_locked (nframes);
3849         return 0;
3850 }
3851
3852 #ifdef __clang__
3853 __attribute__((annotate("realtime")))
3854 #endif
3855 bool
3856 Route::apply_processor_changes_rt ()
3857 {
3858         int emissions = EmitNone;
3859
3860         if (_pending_meter_point != _meter_point) {
3861                 Glib::Threads::RWLock::WriterLock pwl (_processor_lock, Glib::Threads::TRY_LOCK);
3862                 if (pwl.locked()) {
3863                         /* meters always have buffers for 'processor_max_streams'
3864                          * they can be re-positioned without re-allocation */
3865                         if (set_meter_point_unlocked()) {
3866                                 emissions |= EmitMeterChanged | EmitMeterVisibilityChange;;
3867                         } else {
3868                                 emissions |= EmitMeterChanged;
3869                         }
3870                 }
3871         }
3872
3873         bool changed = false;
3874
3875         if (g_atomic_int_get (&_pending_process_reorder)) {
3876                 Glib::Threads::RWLock::WriterLock pwl (_processor_lock, Glib::Threads::TRY_LOCK);
3877                 if (pwl.locked()) {
3878                         apply_processor_order (_pending_processor_order);
3879                         setup_invisible_processors ();
3880                         changed = true;
3881                         g_atomic_int_set (&_pending_process_reorder, 0);
3882                         emissions |= EmitRtProcessorChange;
3883                 }
3884         }
3885         if (changed) {
3886                 set_processor_positions ();
3887                 /* update processor input/output latency
3888                  * (total signal_latency does not change)
3889                  */
3890                 update_signal_latency (true);
3891         }
3892         if (emissions != 0) {
3893                 g_atomic_int_set (&_pending_signals, emissions);
3894                 return true;
3895         }
3896         return (!selfdestruct_sequence.empty ());
3897 }
3898
3899 void
3900 Route::emit_pending_signals ()
3901 {
3902         int sig = g_atomic_int_and (&_pending_signals, 0);
3903         if (sig & EmitMeterChanged) {
3904                 _meter->emit_configuration_changed();
3905                 meter_change (); /* EMIT SIGNAL */
3906                 if (sig & EmitMeterVisibilityChange) {
3907                 processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, true)); /* EMIT SIGNAL */
3908                 } else {
3909                 processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, false)); /* EMIT SIGNAL */
3910                 }
3911         }
3912         if (sig & EmitRtProcessorChange) {
3913                 processors_changed (RouteProcessorChange (RouteProcessorChange::RealTimeChange)); /* EMIT SIGNAL */
3914         }
3915
3916         /* this would be a job for the butler.
3917          * Conceptually we should not take processe/processor locks here.
3918          * OTOH its more efficient (less overhead for summoning the butler and
3919          * telling her what do do) and signal emission is called
3920          * directly after the process callback, which decreases the chance
3921          * of x-runs when taking the locks.
3922          */
3923         while (!selfdestruct_sequence.empty ()) {
3924                 Glib::Threads::Mutex::Lock lx (selfdestruct_lock);
3925                 if (selfdestruct_sequence.empty ()) { break; } // re-check with lock
3926                 boost::shared_ptr<Processor> proc = selfdestruct_sequence.back ().lock ();
3927                 selfdestruct_sequence.pop_back ();
3928                 lx.release ();
3929                 if (proc) {
3930                         remove_processor (proc);
3931                 }
3932         }
3933 }
3934
3935 void
3936 Route::set_meter_point (MeterPoint p, bool force)
3937 {
3938         if (_pending_meter_point == p && !force) {
3939                 return;
3940         }
3941
3942         if (force || !AudioEngine::instance()->running()) {
3943                 bool meter_visibly_changed = false;
3944                 {
3945                         Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
3946                         Glib::Threads::RWLock::WriterLock lm (_processor_lock);
3947                         _pending_meter_point = p;
3948                         if (set_meter_point_unlocked ()) {
3949                                 meter_visibly_changed = true;
3950                         }
3951                 }
3952                 _meter->emit_configuration_changed();
3953                 meter_change (); /* EMIT SIGNAL */
3954                 processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, meter_visibly_changed)); /* EMIT SIGNAL */
3955         } else {
3956                 _pending_meter_point = p;
3957         }
3958 }
3959
3960
3961 #ifdef __clang__
3962 __attribute__((annotate("realtime")))
3963 #endif
3964 bool
3965 Route::set_meter_point_unlocked ()
3966 {
3967 #ifndef NDEBUG
3968         /* Caller must hold process and processor write lock */
3969         assert (!AudioEngine::instance()->process_lock().trylock());
3970         Glib::Threads::RWLock::WriterLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
3971         assert (!lm.locked ());
3972 #endif
3973
3974         _meter_point = _pending_meter_point;
3975
3976         bool meter_was_visible_to_user = _meter->display_to_user ();
3977
3978         if (!_custom_meter_position_noted) {
3979                 maybe_note_meter_position ();
3980         }
3981
3982         if (_meter_point != MeterCustom) {
3983
3984                 _meter->set_display_to_user (false);
3985
3986                 setup_invisible_processors ();
3987
3988         } else {
3989                 _meter->set_display_to_user (true);
3990
3991                 /* If we have a previous position for the custom meter, try to put it there */
3992                 boost::shared_ptr<Processor> after = _processor_after_last_custom_meter.lock ();
3993                 if (after) {
3994                         ProcessorList::iterator i = find (_processors.begin(), _processors.end(), after);
3995                         if (i != _processors.end ()) {
3996                                 _processors.remove (_meter);
3997                                 _processors.insert (i, _meter);
3998                         }
3999                 } else {// at end, right before the mains_out/panner
4000                         _processors.remove (_meter);
4001                         ProcessorList::iterator main = _processors.end();
4002                         _processors.insert (--main, _meter);
4003                 }
4004         }
4005
4006         /* Set up the meter for its new position */
4007
4008         ProcessorList::iterator loc = find (_processors.begin(), _processors.end(), _meter);
4009
4010         ChanCount m_in;
4011
4012         if (loc == _processors.begin()) {
4013                 m_in = _input->n_ports();
4014         } else {
4015                 ProcessorList::iterator before = loc;
4016                 --before;
4017                 m_in = (*before)->output_streams ();
4018         }
4019
4020         _meter->reflect_inputs (m_in);
4021
4022         /* we do not need to reconfigure the processors, because the meter
4023            (a) is always ready to handle processor_max_streams
4024            (b) is always an N-in/N-out processor, and thus moving
4025            it doesn't require any changes to the other processors.
4026         */
4027
4028         /* these should really be done after releasing the lock
4029          * but all those signals are subscribed to with gui_thread()
4030          * so we're safe.
4031          */
4032          return (_meter->display_to_user() != meter_was_visible_to_user);
4033 }
4034
4035 void
4036 Route::listen_position_changed ()
4037 {
4038         {
4039                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
4040                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
4041                 ProcessorState pstate (this);
4042
4043                 if (configure_processors_unlocked (0, &lm)) {
4044                         DEBUG_TRACE (DEBUG::Processors, "---- CONFIGURATION FAILED.\n");
4045                         pstate.restore ();
4046                         configure_processors_unlocked (0, &lm); // it worked before we tried to add it ...
4047                         return;
4048                 }
4049         }
4050
4051         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
4052         _session.set_dirty ();
4053 }
4054
4055 boost::shared_ptr<CapturingProcessor>
4056 Route::add_export_point()
4057 {
4058         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4059         if (!_capturing_processor) {
4060                 lm.release();
4061                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
4062                 Glib::Threads::RWLock::WriterLock lw (_processor_lock);
4063
4064                 /* Align all tracks for stem-export w/o processing.
4065                  * Compensate for all plugins between the this route's disk-reader
4066                  * and the common final downstream output (ie alignment point for playback).
4067                  */
4068                 _capturing_processor.reset (new CapturingProcessor (_session, playback_latency (true)));
4069                 configure_processors_unlocked (0, &lw);
4070                 _capturing_processor->activate ();
4071         }
4072
4073         return _capturing_processor;
4074 }
4075
4076 samplecnt_t
4077 Route::update_signal_latency (bool apply_to_delayline)
4078 {
4079         // TODO: bail out if !active() and set/assume _signal_latency = 0,
4080         // here or in Session::* ? -> also zero send latencies,
4081         // and make sure that re-enabling a route updates things again...
4082
4083         samplecnt_t capt_lat_in = _input->connected_latency (false);
4084         samplecnt_t play_lat_out = _output->connected_latency (true);
4085
4086         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4087
4088         samplecnt_t l_in  = 0;
4089         samplecnt_t l_out = _output->effective_latency ();
4090         for (ProcessorList::reverse_iterator i = _processors.rbegin(); i != _processors.rend(); ++i) {
4091                 if (boost::shared_ptr<Send> snd = boost::dynamic_pointer_cast<Send> (*i)) {
4092                         snd->set_delay_in (l_out + _output->latency());
4093                 }
4094
4095                 if (boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) {
4096                         if (boost::shared_ptr<IO> pio = pi->sidechain_input ()) {
4097                                 samplecnt_t lat = l_out + _output->latency();
4098                                 pio->set_private_port_latencies (lat, true);
4099                                 pio->set_public_port_latencies (lat, true);
4100                         }
4101                 }
4102                 (*i)->set_output_latency (l_out);
4103                 if ((*i)->active ()) { // XXX
4104                         l_out += (*i)->effective_latency ();
4105                 }
4106         }
4107
4108         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: internal signal latency = %2\n", _name, l_out));
4109
4110         _signal_latency = l_out;
4111
4112         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4113
4114                 /* set sidechain, send and insert port latencies */
4115                 if (boost::shared_ptr<PortInsert> pi = boost::dynamic_pointer_cast<PortInsert> (*i)) {
4116                         if (pi->input ()) {
4117                                 /* propagate playback latency from output to input */
4118                                 pi->input ()->set_private_port_latencies (play_lat_out + l_in, true);
4119                         }
4120                         if (pi->output ()) {
4121                                 /* propagate capture latency from input to output */
4122                                 pi->output ()->set_private_port_latencies (capt_lat_in + l_in, false);
4123                         }
4124
4125                 } else if (boost::shared_ptr<Send> snd = boost::dynamic_pointer_cast<Send> (*i)) {
4126                         if (snd->output ()) {
4127                                 /* set capture latency */
4128                                 snd->output ()->set_private_port_latencies (capt_lat_in + l_in, false);
4129                                 /* take send-target's playback latency into account */
4130                                 snd->set_delay_out (snd->output ()->connected_latency (true));
4131                         }
4132                 }
4133
4134                 (*i)->set_input_latency (l_in);
4135                 (*i)->set_playback_offset (_signal_latency + _output->latency ());
4136                 (*i)->set_capture_offset (_input->latency ());
4137                 if ((*i)->active ()) {
4138                         l_in += (*i)->effective_latency ();
4139                 }
4140         }
4141
4142         lm.release ();
4143
4144         if (apply_to_delayline) {
4145                 /* see also Session::post_playback_latency() */
4146                 apply_latency_compensation ();
4147         }
4148
4149         if (_signal_latency != l_out) {
4150                 signal_latency_changed (); /* EMIT SIGNAL */
4151         }
4152
4153         return _signal_latency;
4154 }
4155
4156 void
4157 Route::set_user_latency (samplecnt_t nframes)
4158 {
4159         _output->set_user_latency (nframes);
4160         _session.update_latency_compensation ();
4161 }
4162
4163 void
4164 Route::apply_latency_compensation ()
4165 {
4166         if (_delayline) {
4167                 samplecnt_t old = _delayline->delay ();
4168
4169                 samplecnt_t play_lat_in = _input->connected_latency (true);
4170                 samplecnt_t play_lat_out = _output->connected_latency (true);
4171                 samplecnt_t latcomp = play_lat_in - play_lat_out - _signal_latency;
4172
4173 #if 0 // DEBUG
4174                 samplecnt_t capt_lat_in = _input->connected_latency (false);
4175                 samplecnt_t capt_lat_out = _output->connected_latency (false);
4176                 samplecnt_t latcomp_capt = capt_lat_out - capt_lat_in - _signal_latency;
4177
4178                 cout << "ROUTE " << name() << " delay for " << latcomp << " (c: " << latcomp_capt << ")" << endl;
4179 #endif
4180
4181                 _delayline->set_delay (latcomp > 0 ? latcomp : 0);
4182
4183                 if (old !=  _delayline->delay ()) {
4184                         signal_latency_updated (); /* EMIT SIGNAL */
4185                 }
4186         }
4187 }
4188
4189 void
4190 Route::set_block_size (pframes_t nframes)
4191 {
4192         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4193                 (*i)->set_block_size (nframes);
4194         }
4195
4196         _session.ensure_buffers (n_process_buffers ());
4197 }
4198
4199 void
4200 Route::protect_automation ()
4201 {
4202         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
4203                 (*i)->protect_automation();
4204 }
4205
4206 /** Shift automation forwards from a particular place, thereby inserting time.
4207  *  Adds undo commands for any shifts that are performed.
4208  *
4209  * @param pos Position to start shifting from.
4210  * @param samples Amount to shift forwards by.
4211  */
4212
4213 void
4214 Route::shift (samplepos_t pos, samplecnt_t samples)
4215 {
4216         /* pan automation */
4217         if (_pannable) {
4218                 ControlSet::Controls& c (_pannable->controls());
4219
4220                 for (ControlSet::Controls::const_iterator ci = c.begin(); ci != c.end(); ++ci) {
4221                         boost::shared_ptr<AutomationControl> pc = boost::dynamic_pointer_cast<AutomationControl> (ci->second);
4222                         if (pc) {
4223                                 boost::shared_ptr<AutomationList> al = pc->alist();
4224                                 XMLNode& before = al->get_state ();
4225                                 al->shift (pos, samples);
4226                                 XMLNode& after = al->get_state ();
4227                                 _session.add_command (new MementoCommand<AutomationList> (*al.get(), &before, &after));
4228                         }
4229                 }
4230         }
4231
4232         /* TODO mute automation, MuteControl */
4233
4234         /* processor automation (incl. gain, trim,..) */
4235         {
4236                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4237                 for (ProcessorList::iterator i = _processors.begin (); i != _processors.end (); ++i) {
4238
4239                         set<Evoral::Parameter> parameters = (*i)->what_can_be_automated();
4240
4241                         for (set<Evoral::Parameter>::const_iterator p = parameters.begin (); p != parameters.end (); ++p) {
4242                                 boost::shared_ptr<AutomationControl> ac = (*i)->automation_control (*p);
4243                                 if (ac) {
4244                                         boost::shared_ptr<AutomationList> al = ac->alist();
4245                                         if (al->empty ()) {
4246                                                 continue;
4247                                         }
4248                                         XMLNode &before = al->get_state ();
4249                                         al->shift (pos, samples);
4250                                         XMLNode &after = al->get_state ();
4251                                         _session.add_command (new MementoCommand<AutomationList> (*al.get(), &before, &after));
4252                                 }
4253                         }
4254                 }
4255         }
4256 }
4257
4258 void
4259 Route::set_plugin_state_dir (boost::weak_ptr<Processor> p, const std::string& d)
4260 {
4261         boost::shared_ptr<Processor> processor (p.lock ());
4262         boost::shared_ptr<PluginInsert> pi  = boost::dynamic_pointer_cast<PluginInsert> (processor);
4263         if (!pi) {
4264                 return;
4265         }
4266         pi->set_state_dir (d);
4267 }
4268
4269 int
4270 Route::save_as_template (const string& path, const string& name, const string& description)
4271 {
4272         std::string state_dir = path.substr (0, path.find_last_of ('.')); // strip template_suffix
4273         PBD::Unwinder<std::string> uw (_session._template_state_dir, state_dir);
4274
4275         XMLNode& node (state (true));
4276         node.set_property (X_("name"), name);
4277
4278         node.remove_nodes (X_("description"));
4279         if (!description.empty()) {
4280                 XMLNode* desc = new XMLNode(X_("description"));
4281                 XMLNode* desc_cont = new XMLNode(X_("content"), description);
4282                 desc->add_child_nocopy (*desc_cont);
4283
4284                 node.add_child_nocopy (*desc);
4285         }
4286
4287         XMLTree tree;
4288
4289         IO::set_name_in_state (*node.children().front(), name);
4290
4291         tree.set_root (&node);
4292
4293         /* return zero on success, non-zero otherwise */
4294         return !tree.write (path.c_str());
4295 }
4296
4297
4298 bool
4299 Route::set_name (const string& str)
4300 {
4301         if (str.empty ()) {
4302                 return false;
4303         }
4304
4305         if (str == name()) {
4306                 return true;
4307         }
4308
4309         string newname = Route::ensure_track_or_route_name (str);
4310
4311         if (newname == name()) {
4312                 return true;
4313         }
4314
4315         SessionObject::set_name (newname);
4316
4317         for (uint32_t n = 0 ; ; ++n) {
4318                 boost::shared_ptr<PluginInsert> pi = boost::static_pointer_cast<PluginInsert> (nth_plugin (n));
4319                 if (!pi) {
4320                         break;
4321                 }
4322                 pi->update_sidechain_name ();
4323         }
4324
4325         bool ret = (_input->set_name(newname) && _output->set_name(newname));
4326
4327         if (ret) {
4328                 /* rename the main outs. Leave other IO processors
4329                  * with whatever name they already have, because its
4330                  * just fine as it is (it will not contain the route
4331                  * name if its a port insert, port send or port return).
4332                  */
4333
4334                 if (_main_outs) {
4335                         if (_main_outs->set_name (newname)) {
4336                                 /* XXX returning false here is stupid because
4337                                    we already changed the route name.
4338                                 */
4339                                 return false;
4340                         }
4341                 }
4342         }
4343
4344         return ret;
4345 }
4346
4347 /** Set the name of a route in an XML description.
4348  *  @param node XML <Route> node to set the name in.
4349  *  @param name New name.
4350  */
4351 void
4352 Route::set_name_in_state (XMLNode& node, string const & name)
4353 {
4354         node.set_property (X_("name"), name);
4355
4356         XMLNodeList children = node.children();
4357         for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
4358
4359                 if ((*i)->name() == X_("IO")) {
4360
4361                         IO::set_name_in_state (**i, name);
4362
4363                 } else if ((*i)->name() == X_("Processor")) {
4364
4365                         std::string str;
4366                         if ((*i)->get_property (X_("role"), str) && str == X_("Main")) {
4367                                 (*i)->set_property (X_("name"), name);
4368                         }
4369                 }
4370         }
4371 }
4372
4373 boost::shared_ptr<Send>
4374 Route::internal_send_for (boost::shared_ptr<const Route> target) const
4375 {
4376         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4377
4378         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4379                 boost::shared_ptr<InternalSend> send;
4380
4381                 if ((send = boost::dynamic_pointer_cast<InternalSend>(*i)) != 0) {
4382                         if (send->target_route() == target) {
4383                                 return send;
4384                         }
4385                 }
4386         }
4387
4388         return boost::shared_ptr<Send>();
4389 }
4390
4391 void
4392 Route::set_denormal_protection (bool yn)
4393 {
4394         if (_denormal_protection != yn) {
4395                 _denormal_protection = yn;
4396                 denormal_protection_changed (); /* EMIT SIGNAL */
4397         }
4398 }
4399
4400 bool
4401 Route::denormal_protection () const
4402 {
4403         return _denormal_protection;
4404 }
4405
4406 void
4407 Route::set_active (bool yn, void* src)
4408 {
4409         if (_session.transport_rolling()) {
4410                 return;
4411         }
4412
4413         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_route_active()) {
4414                 _route_group->foreach_route (boost::bind (&Route::set_active, _1, yn, _route_group));
4415                 return;
4416         }
4417
4418         if (_active != yn) {
4419                 _active = yn;
4420                 _input->set_active (yn);
4421                 _output->set_active (yn);
4422                 flush_processors ();
4423                 active_changed (); // EMIT SIGNAL
4424                 _session.set_dirty ();
4425         }
4426 }
4427
4428 boost::shared_ptr<Pannable>
4429 Route::pannable() const
4430 {
4431         return _pannable;
4432 }
4433
4434 boost::shared_ptr<Panner>
4435 Route::panner() const
4436 {
4437         /* may be null ! */
4438         return _main_outs->panner_shell()->panner();
4439 }
4440
4441 boost::shared_ptr<PannerShell>
4442 Route::panner_shell() const
4443 {
4444         return _main_outs->panner_shell();
4445 }
4446
4447 boost::shared_ptr<GainControl>
4448 Route::gain_control() const
4449 {
4450         return _gain_control;
4451 }
4452
4453 boost::shared_ptr<GainControl>
4454 Route::trim_control() const
4455 {
4456         return _trim_control;
4457 }
4458
4459 boost::shared_ptr<PhaseControl>
4460 Route::phase_control() const
4461 {
4462         return _phase_control;
4463 }
4464
4465 boost::shared_ptr<AutomationControl>
4466 Route::get_control (const Evoral::Parameter& param)
4467 {
4468         /* either we own the control or .... */
4469
4470         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(control (param));
4471
4472         if (!c) {
4473
4474                 /* maybe one of our processors does or ... */
4475
4476                 Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
4477                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4478                         if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->control (param))) != 0) {
4479                                 break;
4480                         }
4481                 }
4482         }
4483
4484         if (!c) {
4485
4486                 /* nobody does so we'll make a new one */
4487
4488                 c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
4489                 add_control(c);
4490         }
4491
4492         return c;
4493 }
4494
4495 boost::shared_ptr<Processor>
4496 Route::nth_plugin (uint32_t n) const
4497 {
4498         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4499         ProcessorList::const_iterator i;
4500
4501         for (i = _processors.begin(); i != _processors.end(); ++i) {
4502                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
4503                         if (n-- == 0) {
4504                                 return *i;
4505                         }
4506                 }
4507         }
4508
4509         return boost::shared_ptr<Processor> ();
4510 }
4511
4512 boost::shared_ptr<Processor>
4513 Route::nth_send (uint32_t n) const
4514 {
4515         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4516         ProcessorList::const_iterator i;
4517
4518         for (i = _processors.begin(); i != _processors.end(); ++i) {
4519                 if (boost::dynamic_pointer_cast<Send> (*i)) {
4520
4521                         if ((*i)->name().find (_("Monitor")) == 0) {
4522                                 /* send to monitor section is not considered
4523                                    to be an accessible send.
4524                                 */
4525                                 continue;
4526                         }
4527
4528                         if (n-- == 0) {
4529                                 return *i;
4530                         }
4531                 }
4532         }
4533
4534         return boost::shared_ptr<Processor> ();
4535 }
4536
4537 bool
4538 Route::has_io_processor_named (const string& name)
4539 {
4540         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4541         ProcessorList::iterator i;
4542
4543         for (i = _processors.begin(); i != _processors.end(); ++i) {
4544                 if (boost::dynamic_pointer_cast<Send> (*i) ||
4545                     boost::dynamic_pointer_cast<PortInsert> (*i)) {
4546                         if ((*i)->name() == name) {
4547                                 return true;
4548                         }
4549                 }
4550         }
4551
4552         return false;
4553 }
4554
4555 void
4556 Route::set_processor_positions ()
4557 {
4558         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4559
4560         bool had_amp = false;
4561         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4562                 (*i)->set_pre_fader (!had_amp);
4563                 if (*i == _amp) {
4564                         had_amp = true;
4565                 }
4566         }
4567 }
4568
4569 /** Called when there is a proposed change to the input port count */
4570 bool
4571 Route::input_port_count_changing (ChanCount to)
4572 {
4573         list<pair<ChanCount, ChanCount> > c = try_configure_processors (to, 0);
4574         if (c.empty()) {
4575                 /* The processors cannot be configured with the new input arrangement, so
4576                    block the change.
4577                 */
4578                 return true;
4579         }
4580
4581         /* The change is ok */
4582         return false;
4583 }
4584
4585 /** Called when there is a proposed change to the output port count */
4586 bool
4587 Route::output_port_count_changing (ChanCount to)
4588 {
4589         if (_strict_io && !_in_configure_processors) {
4590                 return true;
4591         }
4592         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4593                 if (processor_out_streams.get(*t) > to.get(*t)) {
4594                         return true;
4595                 }
4596         }
4597         /* The change is ok */
4598         return false;
4599 }
4600
4601 list<string>
4602 Route::unknown_processors () const
4603 {
4604         list<string> p;
4605
4606         if (_session.get_disable_all_loaded_plugins ()) {
4607                 // Do not list "missing plugins" if they are explicitly disabled
4608                 return p;
4609         }
4610
4611         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4612         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4613                 if (boost::dynamic_pointer_cast<UnknownProcessor const> (*i)) {
4614                         p.push_back ((*i)->name ());
4615                 }
4616         }
4617
4618         return p;
4619 }
4620
4621
4622 samplecnt_t
4623 Route::update_port_latencies (PortSet& from, PortSet& to, bool playback, samplecnt_t our_latency) const
4624 {
4625         /* we assume that all our input ports feed all our output ports. its not
4626            universally true, but the alternative is way too corner-case to worry about.
4627         */
4628
4629         LatencyRange all_connections;
4630
4631         if (from.empty()) {
4632                 all_connections.min = 0;
4633                 all_connections.max = 0;
4634         } else {
4635                 all_connections.min = ~((pframes_t) 0);
4636                 all_connections.max = 0;
4637
4638                 /* iterate over all "from" ports and determine the latency range for all of their
4639                    connections to the "outside" (outside of this Route).
4640                 */
4641
4642                 for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
4643
4644                         LatencyRange range;
4645
4646                         p->get_connected_latency_range (range, playback);
4647
4648                         all_connections.min = min (all_connections.min, range.min);
4649                         all_connections.max = max (all_connections.max, range.max);
4650                 }
4651         }
4652
4653         /* set the "from" port latencies to the max/min range of all their connections */
4654
4655         for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
4656                 p->set_private_latency_range (all_connections, playback);
4657         }
4658
4659         /* set the ports "in the direction of the flow" to the same value as above plus our own signal latency */
4660
4661         all_connections.min += our_latency;
4662         all_connections.max += our_latency;
4663
4664         for (PortSet::iterator p = to.begin(); p != to.end(); ++p) {
4665                 p->set_private_latency_range (all_connections, playback);
4666         }
4667
4668         return all_connections.max;
4669 }
4670
4671 samplecnt_t
4672 Route::set_private_port_latencies (bool playback) const
4673 {
4674         samplecnt_t own_latency = 0;
4675
4676         /* Processor list not protected by lock: MUST BE CALLED FROM PROCESS THREAD
4677            OR LATENCY CALLBACK.
4678
4679            This is called (early) from the latency callback. It computes the REAL
4680            latency associated with each port and stores the result as the "private"
4681            latency of the port. A later call to Route::set_public_port_latencies()
4682            sets all ports to the same value to reflect the fact that we do latency
4683            compensation and so all signals are delayed by the same amount as they
4684            flow through ardour.
4685         */
4686
4687         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4688
4689                 if ((*i)->active ()) {
4690                         own_latency += (*i)->effective_latency ();
4691                 }
4692         }
4693
4694         if (playback) {
4695                 /* playback: propagate latency from "outside the route" to outputs to inputs */
4696                 return update_port_latencies (_output->ports (), _input->ports (), true, own_latency);
4697         } else {
4698                 /* capture: propagate latency from "outside the route" to inputs to outputs */
4699                 return update_port_latencies (_input->ports (), _output->ports (), false, own_latency);
4700         }
4701 }
4702
4703 void
4704 Route::set_public_port_latencies (samplecnt_t value, bool playback) const
4705 {
4706         /* publish private latencies */
4707         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4708         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4709                 boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*i);
4710                 if (!iop) {
4711                         continue;
4712                 }
4713                 if (iop->input ()) {
4714                         iop->input ()->set_public_port_latencies (iop->input()->latency(), true);
4715                 }
4716                 if (iop->output ()) {
4717                         iop->output ()->set_public_port_latencies (iop->output()->latency(), false);
4718                 }
4719         }
4720
4721         /* this is called to set the JACK-visible port latencies, which take
4722          * latency compensation into account.
4723          */
4724         _input->set_public_port_latencies (value, playback);
4725         _output->set_public_port_latencies (value, playback);
4726 }
4727
4728 /** Put the invisible processors in the right place in _processors.
4729  *  Must be called with a writer lock on _processor_lock held.
4730  */
4731 #ifdef __clang__
4732 __attribute__((annotate("realtime")))
4733 #endif
4734 void
4735 Route::setup_invisible_processors ()
4736 {
4737 #ifndef NDEBUG
4738         Glib::Threads::RWLock::WriterLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
4739         assert (!lm.locked ());
4740 #endif
4741
4742         if (!_main_outs) {
4743                 /* too early to be doing this stuff */
4744                 return;
4745         }
4746
4747         /* we'll build this new list here and then use it
4748          *
4749          * TODO put the ProcessorList is on the stack for RT-safety.
4750          */
4751
4752         ProcessorList new_processors;
4753         ProcessorList foldback_sends;
4754         ProcessorList::iterator dr;
4755         ProcessorList::iterator dw;
4756
4757         /* find visible processors */
4758
4759         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4760                 boost::shared_ptr<Send> auxsnd = boost::dynamic_pointer_cast<Send> ((*i));
4761                 if ((*i)->display_to_user ()) {
4762                         new_processors.push_back (*i);
4763                 }
4764                 else if (auxsnd && auxsnd->is_foldback ()) {
4765                         foldback_sends.push_back (*i);
4766                 }
4767         }
4768
4769         /* find the amp */
4770
4771         ProcessorList::iterator amp = find (new_processors.begin(), new_processors.end(), _amp);
4772
4773         if (amp == new_processors.end ()) {
4774                 error << string_compose (_("Amp/Fader on Route '%1' went AWOL. Re-added."), name()) << endmsg;
4775                 new_processors.push_front (_amp);
4776                 amp = find (new_processors.begin(), new_processors.end(), _amp);
4777         }
4778
4779         /* and the processor after the amp */
4780
4781         ProcessorList::iterator after_amp = amp;
4782         ++after_amp;
4783
4784         /* Pre-fader METER */
4785
4786         if (_meter && _meter_point == MeterPreFader) {
4787                 /* add meter just before the fader */
4788                 assert (!_meter->display_to_user ());
4789                 new_processors.insert (amp, _meter);
4790         }
4791
4792         /* MAIN OUTS */
4793
4794         assert (_main_outs);
4795         assert (!_main_outs->display_to_user ());
4796         new_processors.push_back (_main_outs);
4797
4798         /* iterator for the main outs */
4799
4800         ProcessorList::iterator main = new_processors.end();
4801         --main;
4802
4803         /* OUTPUT METERING */
4804
4805         if (_meter && (_meter_point == MeterOutput || _meter_point == MeterPostFader)) {
4806                 assert (!_meter->display_to_user ());
4807
4808                 /* add the processor just before or just after the main outs */
4809
4810                 ProcessorList::iterator meter_point = main;
4811
4812                 if (_meter_point == MeterOutput) {
4813                         ++meter_point;
4814                 }
4815                 new_processors.insert (meter_point, _meter);
4816         }
4817
4818         /* Foldback Sends */
4819
4820         for (ProcessorList::iterator i = foldback_sends.begin(); i != foldback_sends.end(); ++i) {
4821                 new_processors.insert (amp, (*i));
4822         }
4823
4824         /* MONITOR SEND */
4825
4826         if (_monitor_send && !is_monitor ()) {
4827                 assert (!_monitor_send->display_to_user ());
4828                 switch (Config->get_listen_position ()) {
4829                 case PreFaderListen:
4830                         switch (Config->get_pfl_position ()) {
4831                         case PFLFromBeforeProcessors:
4832                                 new_processors.push_front (_monitor_send);
4833                                 break;
4834                         case PFLFromAfterProcessors:
4835                                 new_processors.insert (amp, _monitor_send);
4836                                 break;
4837                         }
4838                         _monitor_send->set_can_pan (false);
4839                         break;
4840                 case AfterFaderListen:
4841                         switch (Config->get_afl_position ()) {
4842                         case AFLFromBeforeProcessors:
4843                                 new_processors.insert (after_amp, _monitor_send);
4844                                 break;
4845                         case AFLFromAfterProcessors:
4846                                 new_processors.insert (new_processors.end(), _monitor_send);
4847                                 break;
4848                         }
4849                         _monitor_send->set_can_pan (true);
4850                         break;
4851                 }
4852         }
4853
4854         /* MONITOR CONTROL */
4855
4856         if (_monitor_control && is_monitor ()) {
4857                 assert (!_monitor_control->display_to_user ());
4858                 new_processors.insert (amp, _monitor_control);
4859         }
4860
4861         /* TRIM CONTROL */
4862
4863         ProcessorList::iterator trim = new_processors.end();
4864
4865         if (_trim->active()) {
4866                 assert (!_trim->display_to_user ());
4867                 new_processors.push_front (_trim);
4868                 trim = new_processors.begin();
4869         }
4870
4871         /* INTERNAL RETURN */
4872
4873         /* doing this here means that any monitor control will come after
4874            the return and trim.
4875         */
4876
4877         if (_intreturn) {
4878                 assert (!_intreturn->display_to_user ());
4879                 new_processors.push_front (_intreturn);
4880         }
4881
4882         /* DISK READER & WRITER (for Track objects) */
4883
4884         if (_disk_reader || _disk_writer) {
4885                 switch (_disk_io_point) {
4886                 case DiskIOPreFader:
4887                         if (trim != new_processors.end()) {
4888                                 /* insert BEFORE TRIM */
4889                                 if (_disk_writer) {
4890                                         new_processors.insert (trim, _disk_writer);
4891                                 }
4892                                 if (_disk_reader) {
4893                                         new_processors.insert (trim, _disk_reader);
4894                                 }
4895                         } else {
4896                                 if (_disk_writer) {
4897                                         new_processors.push_front (_disk_writer);
4898                                 }
4899                                 if (_disk_reader) {
4900                                         new_processors.push_front (_disk_reader);
4901                                 }
4902                         }
4903                         break;
4904                 case DiskIOPostFader:
4905                         /* insert BEFORE main outs */
4906                         if (_disk_writer) {
4907                                 new_processors.insert (main, _disk_writer);
4908                         }
4909                         if (_disk_reader) {
4910                                 new_processors.insert (main, _disk_reader);
4911                         }
4912                         break;
4913                 case DiskIOCustom:
4914                         /* reader and writer are visible under this condition, so they
4915                          * are not invisible and thus not handled here.
4916                          */
4917                         break;
4918                 }
4919         }
4920
4921         /* ensure dist-writer is before disk-reader */
4922         if (_disk_reader && _disk_writer) {
4923                 ProcessorList::iterator reader_pos = find (new_processors.begin(), new_processors.end(), _disk_reader);
4924                 ProcessorList::iterator writer_pos = find (new_processors.begin(), new_processors.end(), _disk_writer);
4925                 assert (reader_pos != new_processors.end ());
4926                 assert (writer_pos != new_processors.end ());
4927                 if (std::distance (new_processors.begin(), reader_pos) < std::distance (new_processors.begin(), writer_pos)) {
4928                         new_processors.erase (reader_pos);
4929                         assert (writer_pos == find (new_processors.begin(), new_processors.end(), _disk_writer));
4930                         new_processors.insert (++writer_pos, _disk_reader);
4931                 }
4932         }
4933
4934         /* EXPORT PROCESSOR */
4935         if (_capturing_processor) {
4936                 assert (!_capturing_processor->display_to_user ());
4937                 ProcessorList::iterator reader_pos = find (new_processors.begin(), new_processors.end(), _disk_reader);
4938                 if (reader_pos != new_processors.end()) {
4939                         /* insert after disk-reader */
4940                         new_processors.insert (++reader_pos, _capturing_processor);
4941                 } else {
4942                         ProcessorList::iterator return_pos = find (new_processors.begin(), new_processors.end(), _intreturn);
4943                         /* insert after return */
4944                         if (return_pos != new_processors.end()) {
4945                                 new_processors.insert (++return_pos, _capturing_processor);
4946                         } else {
4947                                 new_processors.push_front (_capturing_processor);
4948                         }
4949                 }
4950         }
4951
4952         /* Polarity Invert */
4953         if (_polarity) {
4954                 ProcessorList::iterator reader_pos = find (new_processors.begin(), new_processors.end(), _disk_reader);
4955                 if (reader_pos != new_processors.end()) {
4956                         /* insert after disk-reader */
4957                         new_processors.insert (++reader_pos, _polarity);
4958                 } else {
4959                         ProcessorList::iterator return_pos = find (new_processors.begin(), new_processors.end(), _intreturn);
4960                         /* insert after return */
4961                         if (return_pos != new_processors.end()) {
4962                                 new_processors.insert (++return_pos, _polarity);
4963                         } else {
4964                                 new_processors.push_front (_polarity);
4965                         }
4966                 }
4967         }
4968
4969         /* Input meter */
4970         if (_meter && _meter_point == MeterInput) {
4971                 /* add meter just before the disk-writer (if any)
4972                  * otherwise at the top, but after the latency delayline
4973                  * (perhaps it should also be after intreturn on busses ??)
4974                  */
4975                 assert (!_meter->display_to_user ());
4976                 ProcessorList::iterator writer_pos = find (new_processors.begin(), new_processors.end(), _disk_writer);
4977                 if (writer_pos != new_processors.end()) {
4978                         /* insert before disk-writer */
4979                         new_processors.insert (writer_pos, _meter);
4980                 } else {
4981                         ProcessorList::iterator return_pos = find (new_processors.begin(), new_processors.end(), _intreturn);
4982                         /* insert after return */
4983                         if (return_pos != new_processors.end()) {
4984                                 new_processors.insert (++return_pos, _meter);
4985                         } else {
4986                                 new_processors.push_front (_meter);
4987                         }
4988                 }
4989         }
4990
4991         if (!is_master() && !is_monitor() && !is_auditioner()) {
4992                 ProcessorList::iterator reader_pos = find (new_processors.begin(), new_processors.end(), _disk_reader);
4993                 if (reader_pos != new_processors.end()) {
4994                         /* insert before disk-reader */
4995                         new_processors.insert (reader_pos, _delayline);
4996                 } else {
4997                         new_processors.push_front (_delayline);
4998                 }
4999         }
5000
5001         _processors = new_processors;
5002
5003         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5004                 if (!(*i)->display_to_user () && !(*i)->enabled () && (*i) != _monitor_send) {
5005                         (*i)->enable (true);
5006                 }
5007         }
5008
5009         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: setup_invisible_processors\n", _name));
5010         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5011                 DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1\n", (*i)->name ()));
5012         }
5013 }
5014
5015 void
5016 Route::unpan ()
5017 {
5018         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
5019         Glib::Threads::RWLock::ReaderLock lp (_processor_lock);
5020
5021         _pannable.reset ();
5022
5023         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5024                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery>(*i);
5025                 if (d) {
5026                         d->unpan ();
5027                 }
5028         }
5029 }
5030
5031 /** If the meter point is `Custom', make a note of where the meter is.
5032  *  This is so that if the meter point is subsequently set to something else,
5033  *  and then back to custom, we can put the meter back where it was last time
5034  *  custom was enabled.
5035  *
5036  *  Must be called with the _processor_lock held.
5037  */
5038 void
5039 Route::maybe_note_meter_position ()
5040 {
5041         if (_meter_point != MeterCustom) {
5042                 return;
5043         }
5044
5045         _custom_meter_position_noted = true;
5046         /* custom meter points range from after trim to before panner/main_outs
5047          * this is a limitation by the current processor UI
5048          */
5049         bool seen_trim = false;
5050         _processor_after_last_custom_meter.reset();
5051         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5052                 if ((*i) == _trim) {
5053                         seen_trim = true;
5054                 }
5055                 if ((*i) == _main_outs) {
5056                         _processor_after_last_custom_meter = *i;
5057                         break;
5058                 }
5059                 if (boost::dynamic_pointer_cast<PeakMeter> (*i)) {
5060                         if (!seen_trim) {
5061                                 _processor_after_last_custom_meter = _trim;
5062                         } else {
5063                                 ProcessorList::iterator j = i;
5064                                 ++j;
5065                                 assert(j != _processors.end ()); // main_outs should be before
5066                                 _processor_after_last_custom_meter = *j;
5067                         }
5068                         break;
5069                 }
5070         }
5071         assert(_processor_after_last_custom_meter.lock());
5072 }
5073
5074 boost::shared_ptr<Processor>
5075 Route::processor_by_id (PBD::ID id) const
5076 {
5077         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5078         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5079                 if ((*i)->id() == id) {
5080                         return *i;
5081                 }
5082         }
5083
5084         return boost::shared_ptr<Processor> ();
5085 }
5086
5087 /** @return what we should be metering; either the data coming from the input
5088  *  IO or the data that is flowing through the route.
5089  */
5090 MeterState
5091 Route::metering_state () const
5092 {
5093         return MeteringRoute;
5094 }
5095
5096 bool
5097 Route::has_external_redirects () const
5098 {
5099         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5100
5101                 /* ignore inactive processors and obviously ignore the main
5102                  * outs since everything has them and we don't care.
5103                  */
5104
5105                 if ((*i)->active() && (*i) != _main_outs && (*i)->does_routing()) {
5106                         return true;;
5107                 }
5108         }
5109
5110         return false;
5111 }
5112
5113 boost::shared_ptr<Processor>
5114 Route::the_instrument () const
5115 {
5116         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5117         return the_instrument_unlocked ();
5118 }
5119
5120 boost::shared_ptr<Processor>
5121 Route::the_instrument_unlocked () const
5122 {
5123         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5124                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*i);
5125                 if (pi && pi->plugin ()->get_info ()->is_instrument ()) {
5126                         return (*i);
5127                 }
5128         }
5129         return boost::shared_ptr<Processor>();
5130 }
5131
5132 bool
5133 Route::is_track()
5134 {
5135         return dynamic_cast<Track*>(this) != 0;
5136 }
5137
5138 void
5139 Route::non_realtime_locate (samplepos_t pos)
5140 {
5141         Automatable::non_realtime_locate (pos);
5142
5143         if (_pannable) {
5144                 _pannable->non_realtime_locate (pos);
5145         }
5146
5147 #if 0 // XXX mayhaps clear delayline here (and at stop?)
5148         if (_delayline) {
5149                 _delayline->flush ();
5150         }
5151 #endif
5152
5153         {
5154                 //Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
5155                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5156
5157                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5158                         (*i)->non_realtime_locate (pos);
5159                 }
5160         }
5161 }
5162
5163 void
5164 Route::fill_buffers_with_input (BufferSet& bufs, boost::shared_ptr<IO> io, pframes_t nframes)
5165 {
5166         size_t n_buffers;
5167         size_t i;
5168
5169         /* MIDI
5170          *
5171          * We don't currently mix MIDI input together, so we don't need the
5172          * complex logic of the audio case.
5173          */
5174
5175         n_buffers = bufs.count().n_midi ();
5176
5177         for (i = 0; i < n_buffers; ++i) {
5178
5179                 boost::shared_ptr<MidiPort> source_port = io->midi (i);
5180                 MidiBuffer& buf (bufs.get_midi (i));
5181
5182                 if (source_port) {
5183                         buf.copy (source_port->get_midi_buffer(nframes));
5184                 } else {
5185                         buf.silence (nframes);
5186                 }
5187         }
5188
5189         /* AUDIO */
5190
5191         n_buffers = bufs.count().n_audio();
5192
5193         size_t n_ports = io->n_ports().n_audio();
5194         float scaling = 1.0f;
5195
5196         if (n_ports > n_buffers) {
5197                 scaling = ((float) n_buffers) / n_ports;
5198         }
5199
5200         for (i = 0; i < n_ports; ++i) {
5201
5202                 /* if there are more ports than buffers, map them onto buffers
5203                  * in a round-robin fashion
5204                  */
5205
5206                 boost::shared_ptr<AudioPort> source_port = io->audio (i);
5207                 AudioBuffer& buf (bufs.get_audio (i%n_buffers));
5208
5209                 if (i < n_buffers) {
5210
5211                         /* first time through just copy a channel into
5212                            the output buffer.
5213                         */
5214
5215                         buf.read_from (source_port->get_audio_buffer (nframes), nframes);
5216
5217                         if (scaling != 1.0f) {
5218                                 buf.apply_gain (scaling, nframes);
5219                         }
5220
5221                 } else {
5222
5223                         /* on subsequent times around, merge data from
5224                          * the port with what is already there
5225                          */
5226
5227                         if (scaling != 1.0f) {
5228                                 buf.accumulate_with_gain_from (source_port->get_audio_buffer (nframes), nframes, 0, scaling);
5229                         } else {
5230                                 buf.accumulate_from (source_port->get_audio_buffer (nframes), nframes);
5231                         }
5232                 }
5233         }
5234
5235         /* silence any remaining buffers */
5236
5237         for (; i < n_buffers; ++i) {
5238                 AudioBuffer& buf (bufs.get_audio (i));
5239                 buf.silence (nframes);
5240         }
5241
5242         /* establish the initial setup of the buffer set, reflecting what was
5243            copied into it. unless, of course, we are the auditioner, in which
5244            case nothing was fed into it from the inputs at all.
5245         */
5246
5247         if (!is_auditioner()) {
5248                 bufs.set_count (io->n_ports());
5249         }
5250 }
5251
5252 boost::shared_ptr<AutomationControl>
5253 Route::pan_azimuth_control() const
5254 {
5255 #ifdef MIXBUS
5256 # undef MIXBUS_PORTS_H
5257 # include "../../gtk2_ardour/mixbus_ports.h"
5258         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5259         if (!plug) {
5260                 return boost::shared_ptr<AutomationControl>();
5261         }
5262         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_channel_post_pan)));
5263 #else
5264         if (!_pannable || !panner()) {
5265                 return boost::shared_ptr<AutomationControl>();
5266         }
5267         return _pannable->pan_azimuth_control;
5268 #endif
5269 }
5270
5271 boost::shared_ptr<AutomationControl>
5272 Route::pan_elevation_control() const
5273 {
5274         if (Profile->get_mixbus() || !_pannable || !panner()) {
5275                 return boost::shared_ptr<AutomationControl>();
5276         }
5277
5278         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5279
5280         if (c.find (PanElevationAutomation) != c.end()) {
5281                 return _pannable->pan_elevation_control;
5282         } else {
5283                 return boost::shared_ptr<AutomationControl>();
5284         }
5285 }
5286 boost::shared_ptr<AutomationControl>
5287 Route::pan_width_control() const
5288 {
5289 #ifdef MIXBUS
5290         if (mixbus() && _ch_pre) {
5291                 //mono blend
5292                 return boost::dynamic_pointer_cast<ARDOUR::AutomationControl>(_ch_pre->control(Evoral::Parameter(PluginAutomation, 0, 5)));
5293         }
5294 #endif
5295         if (Profile->get_mixbus() || !_pannable || !panner()) {
5296                 return boost::shared_ptr<AutomationControl>();
5297         }
5298
5299         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5300
5301         if (c.find (PanWidthAutomation) != c.end()) {
5302                 return _pannable->pan_width_control;
5303         } else {
5304                 return boost::shared_ptr<AutomationControl>();
5305         }
5306 }
5307 boost::shared_ptr<AutomationControl>
5308 Route::pan_frontback_control() const
5309 {
5310         if (Profile->get_mixbus() || !_pannable || !panner()) {
5311                 return boost::shared_ptr<AutomationControl>();
5312         }
5313
5314         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5315
5316         if (c.find (PanFrontBackAutomation) != c.end()) {
5317                 return _pannable->pan_frontback_control;
5318         } else {
5319                 return boost::shared_ptr<AutomationControl>();
5320         }
5321 }
5322 boost::shared_ptr<AutomationControl>
5323 Route::pan_lfe_control() const
5324 {
5325         if (Profile->get_mixbus() || !_pannable || !panner()) {
5326                 return boost::shared_ptr<AutomationControl>();
5327         }
5328
5329         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5330
5331         if (c.find (PanLFEAutomation) != c.end()) {
5332                 return _pannable->pan_lfe_control;
5333         } else {
5334                 return boost::shared_ptr<AutomationControl>();
5335         }
5336 }
5337
5338 uint32_t
5339 Route::eq_band_cnt () const
5340 {
5341         if (Profile->get_mixbus()) {
5342 #ifdef MIXBUS32C
5343                 if (is_master() || mixbus()) {
5344                         return 3;
5345                 } else {
5346                         return 4;
5347                 }
5348 #else
5349                 return 3;
5350 #endif
5351         } else {
5352                 /* Ardour has no well-known EQ object */
5353                 return 0;
5354         }
5355 }
5356
5357 boost::shared_ptr<AutomationControl>
5358 Route::eq_gain_controllable (uint32_t band) const
5359 {
5360 #ifdef MIXBUS
5361         boost::shared_ptr<PluginInsert> eq = ch_eq();
5362
5363         if (!eq) {
5364                 return boost::shared_ptr<AutomationControl>();
5365         }
5366
5367         uint32_t port_number;
5368         if (is_master() || mixbus()) {
5369                 switch (band) {
5370                         case 0: port_number = 4; break;
5371                         case 1: port_number = 3; break;
5372                         case 2: port_number = 2; break;
5373                         default:
5374                                 return boost::shared_ptr<AutomationControl>();
5375                 }
5376         } else {
5377 #ifdef MIXBUS32C
5378                 switch (band) {
5379                         case 0: port_number = 14; break;
5380                         case 1: port_number = 12; break;
5381                         case 2: port_number = 10; break;
5382                         case 3: port_number =  8; break;
5383                         default:
5384                                 return boost::shared_ptr<AutomationControl>();
5385                 }
5386 #else
5387                 switch (band) {
5388                         case 0: port_number = 8; break;
5389                         case 1: port_number = 6; break;
5390                         case 2: port_number = 4; break;
5391                         default:
5392                                 return boost::shared_ptr<AutomationControl>();
5393                 }
5394 #endif
5395         }
5396
5397         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_number)));
5398 #else
5399         return boost::shared_ptr<AutomationControl>();
5400 #endif
5401 }
5402 boost::shared_ptr<AutomationControl>
5403 Route::eq_freq_controllable (uint32_t band) const
5404 {
5405 #ifdef MIXBUS
5406         if (mixbus() || is_master()) {
5407                 /* no frequency controls for mixbusses or master */
5408                 return boost::shared_ptr<AutomationControl>();
5409         }
5410
5411         boost::shared_ptr<PluginInsert> eq = ch_eq();
5412
5413         if (!eq) {
5414                 return boost::shared_ptr<AutomationControl>();
5415         }
5416
5417         uint32_t port_number;
5418 #ifdef MIXBUS32C
5419         switch (band) {
5420                 case 0: port_number = 13; break; // lo
5421                 case 1: port_number = 11; break; // lo mid
5422                 case 2: port_number = 9; break; // hi mid
5423                 case 3: port_number = 7; break; // hi
5424                 default:
5425                         return boost::shared_ptr<AutomationControl>();
5426         }
5427 #else
5428         switch (band) {
5429                 case 0: port_number = 7; break;
5430                 case 1: port_number = 5; break;
5431                 case 2: port_number = 3; break;
5432                 default:
5433                         return boost::shared_ptr<AutomationControl>();
5434         }
5435 #endif
5436
5437         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_number)));
5438 #else
5439         return boost::shared_ptr<AutomationControl>();
5440 #endif
5441 }
5442
5443 boost::shared_ptr<AutomationControl>
5444 Route::eq_q_controllable (uint32_t band) const
5445 {
5446         return boost::shared_ptr<AutomationControl>();
5447 }
5448
5449 boost::shared_ptr<AutomationControl>
5450 Route::eq_shape_controllable (uint32_t band) const
5451 {
5452 #ifdef MIXBUS32C
5453         boost::shared_ptr<PluginInsert> eq = ch_eq();
5454         if (is_master() || mixbus() || !eq) {
5455                 return boost::shared_ptr<AutomationControl>();
5456         }
5457         switch (band) {
5458                 case 0:
5459                         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 4))); // lo bell
5460                         break;
5461                 case 3:
5462                         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 3))); // hi bell
5463                         break;
5464                 default:
5465                         break;
5466         }
5467 #endif
5468         return boost::shared_ptr<AutomationControl>();
5469 }
5470
5471 boost::shared_ptr<AutomationControl>
5472 Route::eq_enable_controllable () const
5473 {
5474 #ifdef MIXBUS
5475         boost::shared_ptr<PluginInsert> eq = ch_eq();
5476
5477         if (!eq) {
5478                 return boost::shared_ptr<AutomationControl>();
5479         }
5480
5481         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 1)));
5482 #else
5483         return boost::shared_ptr<AutomationControl>();
5484 #endif
5485 }
5486
5487 boost::shared_ptr<AutomationControl>
5488 Route::filter_freq_controllable (bool hpf) const
5489 {
5490 #ifdef MIXBUS
5491         boost::shared_ptr<PluginInsert> eq = ch_eq();
5492
5493         if (is_master() || mixbus() || !eq) {
5494                 return boost::shared_ptr<AutomationControl>();
5495         }
5496         if (hpf) {
5497 #ifdef MIXBUS32C
5498                 return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 5))); // HPF freq
5499 #else
5500                 return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 2)));
5501 #endif
5502         } else {
5503 #ifdef MIXBUS32C
5504                 return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 6))); // LPF freq
5505 #else
5506                 return boost::shared_ptr<AutomationControl>();
5507 #endif
5508         }
5509
5510 #else
5511         return boost::shared_ptr<AutomationControl>();
5512 #endif
5513 }
5514
5515 boost::shared_ptr<AutomationControl>
5516 Route::filter_slope_controllable (bool) const
5517 {
5518         return boost::shared_ptr<AutomationControl>();
5519 }
5520
5521 boost::shared_ptr<AutomationControl>
5522 Route::filter_enable_controllable (bool) const
5523 {
5524 #ifdef MIXBUS32C
5525         boost::shared_ptr<PluginInsert> eq = ch_eq();
5526
5527         if (is_master() || mixbus() || !eq) {
5528                 return boost::shared_ptr<AutomationControl>();
5529         }
5530
5531         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 2)));
5532 #else
5533         return boost::shared_ptr<AutomationControl>();
5534 #endif
5535 }
5536
5537 boost::shared_ptr<AutomationControl>
5538 Route::tape_drive_controllable () const
5539 {
5540 #ifdef MIXBUS
5541         if (_ch_pre && mixbus()) {
5542                 return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (_ch_pre->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 4)));
5543         }
5544         if (_ch_pre && is_master()) {
5545                 return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (_ch_pre->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 1)));
5546         }
5547 #endif
5548
5549         return boost::shared_ptr<AutomationControl>();
5550 }
5551
5552 string
5553 Route::eq_band_name (uint32_t band) const
5554 {
5555 #ifdef MIXBUS32C
5556         if (is_master() || mixbus()) {
5557 #endif
5558         if (Profile->get_mixbus()) {
5559                 switch (band) {
5560                         case 0: return _("lo");
5561                         case 1: return _("mid");
5562                         case 2: return _("hi");
5563                         default: return string();
5564                 }
5565         } else {
5566                 return string ();
5567         }
5568 #ifdef MIXBUS32C
5569         } else {
5570                 switch (band) {
5571                         case 0: return _("lo");
5572                         case 1: return _("lm");
5573                         case 2: return _("hm");
5574                         case 3: return _("hi");
5575                         default: return string();
5576                 }
5577         }
5578 #endif
5579 }
5580
5581 boost::shared_ptr<AutomationControl>
5582 Route::comp_enable_controllable () const
5583 {
5584 #ifdef MIXBUS
5585         boost::shared_ptr<PluginInsert> comp = ch_comp();
5586
5587         if (!comp) {
5588                 return boost::shared_ptr<AutomationControl>();
5589         }
5590
5591         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 1)));
5592 #else
5593         return boost::shared_ptr<AutomationControl>();
5594 #endif
5595 }
5596 boost::shared_ptr<AutomationControl>
5597 Route::comp_threshold_controllable () const
5598 {
5599 #ifdef MIXBUS
5600         boost::shared_ptr<PluginInsert> comp = ch_comp();
5601
5602         if (!comp) {
5603                 return boost::shared_ptr<AutomationControl>();
5604         }
5605
5606         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 2)));
5607
5608 #else
5609         return boost::shared_ptr<AutomationControl>();
5610 #endif
5611 }
5612 boost::shared_ptr<AutomationControl>
5613 Route::comp_speed_controllable () const
5614 {
5615 #ifdef MIXBUS
5616         boost::shared_ptr<PluginInsert> comp = ch_comp();
5617
5618         if (!comp) {
5619                 return boost::shared_ptr<AutomationControl>();
5620         }
5621
5622         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 3)));
5623 #else
5624         return boost::shared_ptr<AutomationControl>();
5625 #endif
5626 }
5627 boost::shared_ptr<AutomationControl>
5628 Route::comp_mode_controllable () const
5629 {
5630 #ifdef MIXBUS
5631         boost::shared_ptr<PluginInsert> comp = ch_comp();
5632
5633         if (!comp) {
5634                 return boost::shared_ptr<AutomationControl>();
5635         }
5636
5637         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 4)));
5638 #else
5639         return boost::shared_ptr<AutomationControl>();
5640 #endif
5641 }
5642 boost::shared_ptr<AutomationControl>
5643 Route::comp_makeup_controllable () const
5644 {
5645 #ifdef MIXBUS
5646         boost::shared_ptr<PluginInsert> comp = ch_comp();
5647
5648         if (!comp) {
5649                 return boost::shared_ptr<AutomationControl>();
5650         }
5651
5652         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 5)));
5653 #else
5654         return boost::shared_ptr<AutomationControl>();
5655 #endif
5656 }
5657 boost::shared_ptr<ReadOnlyControl>
5658 Route::comp_redux_controllable () const
5659 {
5660 #ifdef MIXBUS
5661         boost::shared_ptr<PluginInsert> comp = ch_comp();
5662
5663         if (!comp) {
5664                 return boost::shared_ptr<ReadOnlyControl>();
5665         }
5666         if (is_master()) {
5667                 return comp->control_output (2);
5668         } else {
5669                 return comp->control_output (6);
5670         }
5671
5672 #else
5673         return boost::shared_ptr<ReadOnlyControl>();
5674 #endif
5675 }
5676
5677 string
5678 Route::comp_mode_name (uint32_t mode) const
5679 {
5680 #ifdef MIXBUS
5681         switch (mode) {
5682         case 0:
5683                 return _("Leveler");
5684         case 1:
5685                 return _("Compressor");
5686         case 2:
5687                 return _("Limiter");
5688         case 3:
5689                 return mixbus() ? _("Sidechain") : _("Limiter");
5690         }
5691
5692         return _("???");
5693 #else
5694         return _("???");
5695 #endif
5696 }
5697
5698 string
5699 Route::comp_speed_name (uint32_t mode) const
5700 {
5701 #ifdef MIXBUS
5702         switch (mode) {
5703         case 0:
5704                 return _("Attk");
5705         case 1:
5706                 return _("Ratio");
5707         case 2:
5708         case 3:
5709                 return _("Rels");
5710         }
5711         return _("???");
5712 #else
5713         return _("???");
5714 #endif
5715 }
5716
5717 boost::shared_ptr<AutomationControl>
5718 Route::send_pan_azi_controllable (uint32_t n) const
5719 {
5720 #ifdef  MIXBUS
5721 # undef MIXBUS_PORTS_H
5722 # include "../../gtk2_ardour/mixbus_ports.h"
5723         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5724         if (plug && !mixbus()) {
5725                 uint32_t port_id = 0;
5726                 switch (n) {
5727 # ifdef MIXBUS32C
5728                         case  0: port_id = port_channel_post_aux0_pan; break;  //32c mb "pan" controls use zero-based names, unlike levels. ugh
5729                         case  1: port_id = port_channel_post_aux1_pan; break;
5730                         case  2: port_id = port_channel_post_aux2_pan; break;
5731                         case  3: port_id = port_channel_post_aux3_pan; break;
5732                         case  4: port_id = port_channel_post_aux4_pan; break;
5733                         case  5: port_id = port_channel_post_aux5_pan; break;
5734                         case  6: port_id = port_channel_post_aux6_pan; break;
5735                         case  7: port_id = port_channel_post_aux7_pan; break;
5736                         case  8: port_id = port_channel_post_aux8_pan; break;
5737                         case  9: port_id = port_channel_post_aux9_pan; break;
5738                         case 10: port_id = port_channel_post_aux10_pan; break;
5739                         case 11: port_id = port_channel_post_aux11_pan; break;
5740 # endif
5741                         default:
5742                                 break;
5743                 }
5744
5745                 if (port_id > 0) {
5746                         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_id)));
5747                 }
5748         }
5749 #endif
5750
5751         return boost::shared_ptr<AutomationControl>();
5752 }
5753
5754 boost::shared_ptr<AutomationControl>
5755 Route::send_level_controllable (uint32_t n) const
5756 {
5757 #ifdef  MIXBUS
5758 # undef MIXBUS_PORTS_H
5759 # include "../../gtk2_ardour/mixbus_ports.h"
5760         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5761         if (plug && !mixbus()) {
5762                 uint32_t port_id = 0;
5763                 switch (n) {
5764                         case  0: port_id = port_channel_post_aux1_level; break;
5765                         case  1: port_id = port_channel_post_aux2_level; break;
5766                         case  2: port_id = port_channel_post_aux3_level; break;
5767                         case  3: port_id = port_channel_post_aux4_level; break;
5768                         case  4: port_id = port_channel_post_aux5_level; break;
5769                         case  5: port_id = port_channel_post_aux6_level; break;
5770                         case  6: port_id = port_channel_post_aux7_level; break;
5771                         case  7: port_id = port_channel_post_aux8_level; break;
5772 # ifdef MIXBUS32C
5773                         case  8: port_id = port_channel_post_aux9_level; break;
5774                         case  9: port_id = port_channel_post_aux10_level; break;
5775                         case 10: port_id = port_channel_post_aux11_level; break;
5776                         case 11: port_id = port_channel_post_aux12_level; break;
5777 # endif
5778                         default:
5779                                 break;
5780                 }
5781
5782                 if (port_id > 0) {
5783                         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_id)));
5784                 }
5785 # ifdef MIXBUS32C
5786                 assert (n > 11);
5787                 n -= 12;
5788 # else
5789                 assert (n > 7);
5790                 n -= 8;
5791 # endif
5792         }
5793 #endif
5794         boost::shared_ptr<Send> s = boost::dynamic_pointer_cast<Send>(nth_send (n));
5795         if (!s) {
5796                 return boost::shared_ptr<AutomationControl>();
5797         }
5798         return s->gain_control ();
5799 }
5800
5801 boost::shared_ptr<AutomationControl>
5802 Route::send_enable_controllable (uint32_t n) const
5803 {
5804 #ifdef  MIXBUS
5805 # undef MIXBUS_PORTS_H
5806 # include "../../gtk2_ardour/mixbus_ports.h"
5807         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5808         if (plug && !mixbus()) {
5809                 uint32_t port_id = 0;
5810                 switch (n) {
5811                         case  0: port_id = port_channel_post_aux1_asgn; break;
5812                         case  1: port_id = port_channel_post_aux2_asgn; break;
5813                         case  2: port_id = port_channel_post_aux3_asgn; break;
5814                         case  3: port_id = port_channel_post_aux4_asgn; break;
5815                         case  4: port_id = port_channel_post_aux5_asgn; break;
5816                         case  5: port_id = port_channel_post_aux6_asgn; break;
5817                         case  6: port_id = port_channel_post_aux7_asgn; break;
5818                         case  7: port_id = port_channel_post_aux8_asgn; break;
5819 # ifdef MIXBUS32C
5820                         case  8: port_id = port_channel_post_aux9_asgn; break;
5821                         case  9: port_id = port_channel_post_aux10_asgn; break;
5822                         case 10: port_id = port_channel_post_aux11_asgn; break;
5823                         case 11: port_id = port_channel_post_aux12_asgn; break;
5824 # endif
5825                         default:
5826                                 break;
5827                 }
5828
5829                 if (port_id > 0) {
5830                         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_id)));
5831                 }
5832 # ifdef MIXBUS32C
5833                 assert (n > 11);
5834                 n -= 12;
5835 # else
5836                 assert (n > 7);
5837                 n -= 8;
5838 # endif
5839         }
5840 #endif
5841         /* although Ardour sends have enable/disable as part of the Processor
5842          * API, it is not exposed as a controllable.
5843          *
5844          * XXX: we should fix this (make it click-free, automatable enable-control)
5845          */
5846         return boost::shared_ptr<AutomationControl>();
5847 }
5848
5849 string
5850 Route::send_name (uint32_t n) const
5851 {
5852 #ifdef MIXBUS
5853         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5854         if (plug && !mixbus()) {
5855 # ifdef MIXBUS32C
5856                 if (n < 12) {
5857                         return _session.get_mixbus (n)->name();
5858                 }
5859                 n -= 12;
5860 #else
5861                 if (n < 8) {
5862                         return _session.get_mixbus (n)->name();
5863                 }
5864                 n -= 8;
5865 # endif
5866         }
5867 #endif
5868         boost::shared_ptr<Processor> p = nth_send (n);
5869         if (p) {
5870                 return p->name();
5871         } else {
5872                 return string();
5873         }
5874 }
5875
5876 boost::shared_ptr<AutomationControl>
5877 Route::master_send_enable_controllable () const
5878 {
5879 #ifdef  MIXBUS
5880         if (is_master() || is_monitor() || is_auditioner()) {
5881                 return boost::shared_ptr<AutomationControl>();
5882         }
5883
5884         boost::shared_ptr<ARDOUR::PluginInsert> plug = mixbus() ? ch_pre () : ch_post();
5885         if (!plug) {
5886                 return boost::shared_ptr<AutomationControl>();
5887         }
5888         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, mixbus() ? 3 : 19)));
5889 #else
5890         return boost::shared_ptr<AutomationControl>();
5891 #endif
5892 }
5893
5894 bool
5895 Route::slaved () const
5896 {
5897         if (!_gain_control) {
5898                 return false;
5899         }
5900         /* just test one particular control, not all of them */
5901         return _gain_control->slaved ();
5902 }
5903
5904 bool
5905 Route::slaved_to (boost::shared_ptr<VCA> vca) const
5906 {
5907         if (!vca || !_gain_control) {
5908                 return false;
5909         }
5910
5911         /* just test one particular control, not all of them */
5912
5913         return _gain_control->slaved_to (vca->gain_control());
5914 }
5915
5916 bool
5917 Route::muted_by_others_soloing () const
5918 {
5919         if (!can_be_muted_by_others ()) {
5920                 return false;
5921         }
5922
5923         return  _session.soloing() && !_solo_control->soloed() && !_solo_isolate_control->solo_isolated();
5924 }
5925
5926 void
5927 Route::clear_all_solo_state ()
5928 {
5929         _solo_control->clear_all_solo_state ();
5930 }
5931
5932 boost::shared_ptr<AutomationControl>
5933 Route::automation_control_recurse (PBD::ID const & id) const
5934 {
5935         boost::shared_ptr<AutomationControl> ac = Automatable::automation_control (id);
5936
5937         if (ac) {
5938                 return ac;
5939         }
5940
5941         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5942
5943         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5944                 if ((ac = (*i)->automation_control (id))) {
5945                         return ac;
5946                 }
5947         }
5948
5949         return boost::shared_ptr<AutomationControl> ();
5950 }
5951
5952 SlavableControlList
5953 Route::slavables () const
5954 {
5955         SlavableControlList rv;
5956         rv.push_back (_gain_control);
5957         rv.push_back (_mute_control);
5958         rv.push_back (_solo_control);
5959         return rv;
5960 }
5961
5962 void
5963 Route::set_disk_io_point (DiskIOPoint diop)
5964 {
5965         bool display = false;
5966
5967         cerr << "set disk io to " << enum_2_string (diop) << endl;
5968
5969         switch (diop) {
5970         case DiskIOCustom:
5971                 display = true;
5972                 break;
5973         default:
5974                 display = false;
5975         }
5976
5977         if (_disk_writer) {
5978                 _disk_writer->set_display_to_user (display);
5979         }
5980
5981         if (_disk_reader) {
5982                 _disk_reader->set_display_to_user (display);
5983         }
5984
5985         const bool changed = (diop != _disk_io_point);
5986
5987         _disk_io_point = diop;
5988
5989         if (changed) {
5990                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
5991                 configure_processors (0);
5992         }
5993
5994         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
5995 }
5996
5997 void
5998 Route::set_loop (Location* l)
5999 {
6000         _loop_location = l;
6001         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
6002         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
6003                 (*i)->set_loop (l);
6004         }
6005 }
6006
6007 #ifdef USE_TRACKS_CODE_FEATURES
6008
6009 /* This is the Tracks version of Track::monitoring_state().
6010  *
6011  * Ardour developers: try to flag or fix issues if parts of the libardour API
6012  * change in ways that invalidate this
6013  */
6014
6015 MonitorState
6016 Route::monitoring_state () const
6017 {
6018         /* Explicit requests */
6019
6020         if (_monitoring != MonitorInput) {
6021                 return MonitoringInput;
6022         }
6023
6024         if (_monitoring & MonitorDisk) {
6025                 return MonitoringDisk;
6026         }
6027
6028         /* This is an implementation of the truth table in doc/monitor_modes.pdf;
6029            I don't think it's ever going to be too pretty too look at.
6030         */
6031
6032         // GZ: NOT USED IN TRACKS
6033         //bool const auto_input = _session.config.get_auto_input ();
6034         //bool const software_monitor = Config->get_monitoring_model() == SoftwareMonitoring;
6035         //bool const tape_machine_mode = Config->get_tape_machine_mode ();
6036
6037         bool const roll = _session.transport_rolling ();
6038         bool const track_rec = _diskstream->record_enabled ();
6039         bool session_rec = _session.actively_recording ();
6040
6041         if (track_rec) {
6042
6043                 if (!session_rec && roll) {
6044                         return MonitoringDisk;
6045                 } else {
6046                         return MonitoringInput;
6047                 }
6048
6049         } else {
6050
6051                 if (roll) {
6052                         return MonitoringDisk;
6053                 }
6054         }
6055
6056         return MonitoringSilence;
6057 }
6058
6059 #else
6060
6061 /* This is the Ardour/Mixbus version of Track::monitoring_state().
6062  *
6063  * Tracks developers: do NOT modify this method under any circumstances.
6064  */
6065
6066 MonitorState
6067 Route::monitoring_state () const
6068 {
6069         if (!_disk_reader) {
6070                 return MonitoringInput;
6071         }
6072
6073         /* Explicit requests */
6074         MonitorChoice m (_monitoring_control->monitoring_choice());
6075
6076         if (m != MonitorAuto) {
6077
6078                 MonitorState ms ((MonitorState) 0);
6079
6080                 if (m & MonitorInput) {
6081                         ms = MonitoringInput;
6082                 }
6083
6084                 if (m & MonitorDisk) {
6085                         ms = MonitorState (ms | MonitoringDisk);
6086                 }
6087
6088                 return ms;
6089         }
6090
6091         switch (_session.config.get_session_monitoring ()) {
6092                 case MonitorDisk:
6093                         return MonitoringDisk;
6094                         break;
6095                 case MonitorInput:
6096                         return MonitoringInput;
6097                         break;
6098                 default:
6099                         break;
6100         }
6101
6102         return get_auto_monitoring_state();
6103 }
6104 #endif