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