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