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