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