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