Do not create automation when shifting (insert/remove time)
[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                                         if (al->empty ()) {
4228                                                 continue;
4229                                         }
4230                                         XMLNode &before = al->get_state ();
4231                                         al->shift (pos, samples);
4232                                         XMLNode &after = al->get_state ();
4233                                         _session.add_command (new MementoCommand<AutomationList> (*al.get(), &before, &after));
4234                                 }
4235                         }
4236                 }
4237         }
4238 }
4239
4240 void
4241 Route::set_plugin_state_dir (boost::weak_ptr<Processor> p, const std::string& d)
4242 {
4243         boost::shared_ptr<Processor> processor (p.lock ());
4244         boost::shared_ptr<PluginInsert> pi  = boost::dynamic_pointer_cast<PluginInsert> (processor);
4245         if (!pi) {
4246                 return;
4247         }
4248         pi->set_state_dir (d);
4249 }
4250
4251 int
4252 Route::save_as_template (const string& path, const string& name, const string& description)
4253 {
4254         std::string state_dir = path.substr (0, path.find_last_of ('.')); // strip template_suffix
4255         PBD::Unwinder<std::string> uw (_session._template_state_dir, state_dir);
4256
4257         XMLNode& node (state (true));
4258         node.set_property (X_("name"), name);
4259
4260         node.remove_nodes (X_("description"));
4261         if (!description.empty()) {
4262                 XMLNode* desc = new XMLNode(X_("description"));
4263                 XMLNode* desc_cont = new XMLNode(X_("content"), description);
4264                 desc->add_child_nocopy (*desc_cont);
4265
4266                 node.add_child_nocopy (*desc);
4267         }
4268
4269         XMLTree tree;
4270
4271         IO::set_name_in_state (*node.children().front(), name);
4272
4273         tree.set_root (&node);
4274
4275         /* return zero on success, non-zero otherwise */
4276         return !tree.write (path.c_str());
4277 }
4278
4279
4280 bool
4281 Route::set_name (const string& str)
4282 {
4283         if (str.empty ()) {
4284                 return false;
4285         }
4286
4287         if (str == name()) {
4288                 return true;
4289         }
4290
4291         string newname = Route::ensure_track_or_route_name (str);
4292
4293         if (newname == name()) {
4294                 return true;
4295         }
4296
4297         SessionObject::set_name (newname);
4298
4299         for (uint32_t n = 0 ; ; ++n) {
4300                 boost::shared_ptr<PluginInsert> pi = boost::static_pointer_cast<PluginInsert> (nth_plugin (n));
4301                 if (!pi) {
4302                         break;
4303                 }
4304                 pi->update_sidechain_name ();
4305         }
4306
4307         bool ret = (_input->set_name(newname) && _output->set_name(newname));
4308
4309         if (ret) {
4310                 /* rename the main outs. Leave other IO processors
4311                  * with whatever name they already have, because its
4312                  * just fine as it is (it will not contain the route
4313                  * name if its a port insert, port send or port return).
4314                  */
4315
4316                 if (_main_outs) {
4317                         if (_main_outs->set_name (newname)) {
4318                                 /* XXX returning false here is stupid because
4319                                    we already changed the route name.
4320                                 */
4321                                 return false;
4322                         }
4323                 }
4324         }
4325
4326         return ret;
4327 }
4328
4329 /** Set the name of a route in an XML description.
4330  *  @param node XML <Route> node to set the name in.
4331  *  @param name New name.
4332  */
4333 void
4334 Route::set_name_in_state (XMLNode& node, string const & name)
4335 {
4336         node.set_property (X_("name"), name);
4337
4338         XMLNodeList children = node.children();
4339         for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
4340
4341                 if ((*i)->name() == X_("IO")) {
4342
4343                         IO::set_name_in_state (**i, name);
4344
4345                 } else if ((*i)->name() == X_("Processor")) {
4346
4347                         std::string str;
4348                         if ((*i)->get_property (X_("role"), str) && str == X_("Main")) {
4349                                 (*i)->set_property (X_("name"), name);
4350                         }
4351                 }
4352         }
4353 }
4354
4355 boost::shared_ptr<Send>
4356 Route::internal_send_for (boost::shared_ptr<const Route> target) const
4357 {
4358         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4359
4360         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4361                 boost::shared_ptr<InternalSend> send;
4362
4363                 if ((send = boost::dynamic_pointer_cast<InternalSend>(*i)) != 0) {
4364                         if (send->target_route() == target) {
4365                                 return send;
4366                         }
4367                 }
4368         }
4369
4370         return boost::shared_ptr<Send>();
4371 }
4372
4373 void
4374 Route::set_denormal_protection (bool yn)
4375 {
4376         if (_denormal_protection != yn) {
4377                 _denormal_protection = yn;
4378                 denormal_protection_changed (); /* EMIT SIGNAL */
4379         }
4380 }
4381
4382 bool
4383 Route::denormal_protection () const
4384 {
4385         return _denormal_protection;
4386 }
4387
4388 void
4389 Route::set_active (bool yn, void* src)
4390 {
4391         if (_session.transport_rolling()) {
4392                 return;
4393         }
4394
4395         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_route_active()) {
4396                 _route_group->foreach_route (boost::bind (&Route::set_active, _1, yn, _route_group));
4397                 return;
4398         }
4399
4400         if (_active != yn) {
4401                 _active = yn;
4402                 _input->set_active (yn);
4403                 _output->set_active (yn);
4404                 flush_processors ();
4405                 active_changed (); // EMIT SIGNAL
4406                 _session.set_dirty ();
4407         }
4408 }
4409
4410 boost::shared_ptr<Pannable>
4411 Route::pannable() const
4412 {
4413         return _pannable;
4414 }
4415
4416 boost::shared_ptr<Panner>
4417 Route::panner() const
4418 {
4419         /* may be null ! */
4420         return _main_outs->panner_shell()->panner();
4421 }
4422
4423 boost::shared_ptr<PannerShell>
4424 Route::panner_shell() const
4425 {
4426         return _main_outs->panner_shell();
4427 }
4428
4429 boost::shared_ptr<GainControl>
4430 Route::gain_control() const
4431 {
4432         return _gain_control;
4433 }
4434
4435 boost::shared_ptr<GainControl>
4436 Route::trim_control() const
4437 {
4438         return _trim_control;
4439 }
4440
4441 boost::shared_ptr<PhaseControl>
4442 Route::phase_control() const
4443 {
4444         return _phase_control;
4445 }
4446
4447 boost::shared_ptr<AutomationControl>
4448 Route::get_control (const Evoral::Parameter& param)
4449 {
4450         /* either we own the control or .... */
4451
4452         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(control (param));
4453
4454         if (!c) {
4455
4456                 /* maybe one of our processors does or ... */
4457
4458                 Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
4459                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4460                         if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->control (param))) != 0) {
4461                                 break;
4462                         }
4463                 }
4464         }
4465
4466         if (!c) {
4467
4468                 /* nobody does so we'll make a new one */
4469
4470                 c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
4471                 add_control(c);
4472         }
4473
4474         return c;
4475 }
4476
4477 boost::shared_ptr<Processor>
4478 Route::nth_plugin (uint32_t n) const
4479 {
4480         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4481         ProcessorList::const_iterator i;
4482
4483         for (i = _processors.begin(); i != _processors.end(); ++i) {
4484                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
4485                         if (n-- == 0) {
4486                                 return *i;
4487                         }
4488                 }
4489         }
4490
4491         return boost::shared_ptr<Processor> ();
4492 }
4493
4494 boost::shared_ptr<Processor>
4495 Route::nth_send (uint32_t n) const
4496 {
4497         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4498         ProcessorList::const_iterator i;
4499
4500         for (i = _processors.begin(); i != _processors.end(); ++i) {
4501                 if (boost::dynamic_pointer_cast<Send> (*i)) {
4502
4503                         if ((*i)->name().find (_("Monitor")) == 0) {
4504                                 /* send to monitor section is not considered
4505                                    to be an accessible send.
4506                                 */
4507                                 continue;
4508                         }
4509
4510                         if (n-- == 0) {
4511                                 return *i;
4512                         }
4513                 }
4514         }
4515
4516         return boost::shared_ptr<Processor> ();
4517 }
4518
4519 bool
4520 Route::has_io_processor_named (const string& name)
4521 {
4522         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4523         ProcessorList::iterator i;
4524
4525         for (i = _processors.begin(); i != _processors.end(); ++i) {
4526                 if (boost::dynamic_pointer_cast<Send> (*i) ||
4527                     boost::dynamic_pointer_cast<PortInsert> (*i)) {
4528                         if ((*i)->name() == name) {
4529                                 return true;
4530                         }
4531                 }
4532         }
4533
4534         return false;
4535 }
4536
4537 void
4538 Route::set_processor_positions ()
4539 {
4540         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4541
4542         bool had_amp = false;
4543         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4544                 (*i)->set_pre_fader (!had_amp);
4545                 if (*i == _amp) {
4546                         had_amp = true;
4547                 }
4548         }
4549 }
4550
4551 /** Called when there is a proposed change to the input port count */
4552 bool
4553 Route::input_port_count_changing (ChanCount to)
4554 {
4555         list<pair<ChanCount, ChanCount> > c = try_configure_processors (to, 0);
4556         if (c.empty()) {
4557                 /* The processors cannot be configured with the new input arrangement, so
4558                    block the change.
4559                 */
4560                 return true;
4561         }
4562
4563         /* The change is ok */
4564         return false;
4565 }
4566
4567 /** Called when there is a proposed change to the output port count */
4568 bool
4569 Route::output_port_count_changing (ChanCount to)
4570 {
4571         if (_strict_io && !_in_configure_processors) {
4572                 return true;
4573         }
4574         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4575                 if (processor_out_streams.get(*t) > to.get(*t)) {
4576                         return true;
4577                 }
4578         }
4579         /* The change is ok */
4580         return false;
4581 }
4582
4583 list<string>
4584 Route::unknown_processors () const
4585 {
4586         list<string> p;
4587
4588         if (_session.get_disable_all_loaded_plugins ()) {
4589                 // Do not list "missing plugins" if they are explicitly disabled
4590                 return p;
4591         }
4592
4593         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4594         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4595                 if (boost::dynamic_pointer_cast<UnknownProcessor const> (*i)) {
4596                         p.push_back ((*i)->name ());
4597                 }
4598         }
4599
4600         return p;
4601 }
4602
4603
4604 samplecnt_t
4605 Route::update_port_latencies (PortSet& from, PortSet& to, bool playback, samplecnt_t our_latency) const
4606 {
4607         /* we assume that all our input ports feed all our output ports. its not
4608            universally true, but the alternative is way too corner-case to worry about.
4609         */
4610
4611         LatencyRange all_connections;
4612
4613         if (from.empty()) {
4614                 all_connections.min = 0;
4615                 all_connections.max = 0;
4616         } else {
4617                 all_connections.min = ~((pframes_t) 0);
4618                 all_connections.max = 0;
4619
4620                 /* iterate over all "from" ports and determine the latency range for all of their
4621                    connections to the "outside" (outside of this Route).
4622                 */
4623
4624                 for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
4625
4626                         LatencyRange range;
4627
4628                         p->get_connected_latency_range (range, playback);
4629
4630                         all_connections.min = min (all_connections.min, range.min);
4631                         all_connections.max = max (all_connections.max, range.max);
4632                 }
4633         }
4634
4635         /* set the "from" port latencies to the max/min range of all their connections */
4636
4637         for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
4638                 p->set_private_latency_range (all_connections, playback);
4639         }
4640
4641         /* set the ports "in the direction of the flow" to the same value as above plus our own signal latency */
4642
4643         all_connections.min += our_latency;
4644         all_connections.max += our_latency;
4645
4646         for (PortSet::iterator p = to.begin(); p != to.end(); ++p) {
4647                 p->set_private_latency_range (all_connections, playback);
4648         }
4649
4650         return all_connections.max;
4651 }
4652
4653 samplecnt_t
4654 Route::set_private_port_latencies (bool playback) const
4655 {
4656         samplecnt_t own_latency = 0;
4657
4658         /* Processor list not protected by lock: MUST BE CALLED FROM PROCESS THREAD
4659            OR LATENCY CALLBACK.
4660
4661            This is called (early) from the latency callback. It computes the REAL
4662            latency associated with each port and stores the result as the "private"
4663            latency of the port. A later call to Route::set_public_port_latencies()
4664            sets all ports to the same value to reflect the fact that we do latency
4665            compensation and so all signals are delayed by the same amount as they
4666            flow through ardour.
4667         */
4668
4669         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4670
4671                 if ((*i)->active ()) {
4672                         own_latency += (*i)->effective_latency ();
4673                 }
4674         }
4675
4676         if (playback) {
4677                 /* playback: propagate latency from "outside the route" to outputs to inputs */
4678                 return update_port_latencies (_output->ports (), _input->ports (), true, own_latency);
4679         } else {
4680                 /* capture: propagate latency from "outside the route" to inputs to outputs */
4681                 return update_port_latencies (_input->ports (), _output->ports (), false, own_latency);
4682         }
4683 }
4684
4685 void
4686 Route::set_public_port_latencies (samplecnt_t value, bool playback) const
4687 {
4688         /* publish private latencies */
4689         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4690         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4691                 boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*i);
4692                 if (!iop) {
4693                         continue;
4694                 }
4695                 if (iop->input ()) {
4696                         iop->input ()->set_public_port_latencies (iop->input()->latency(), true);
4697                 }
4698                 if (iop->output ()) {
4699                         iop->output ()->set_public_port_latencies (iop->output()->latency(), false);
4700                 }
4701         }
4702
4703         /* this is called to set the JACK-visible port latencies, which take
4704          * latency compensation into account.
4705          */
4706         _input->set_public_port_latencies (value, playback);
4707         _output->set_public_port_latencies (value, playback);
4708 }
4709
4710 /** Put the invisible processors in the right place in _processors.
4711  *  Must be called with a writer lock on _processor_lock held.
4712  */
4713 #ifdef __clang__
4714 __attribute__((annotate("realtime")))
4715 #endif
4716 void
4717 Route::setup_invisible_processors ()
4718 {
4719 #ifndef NDEBUG
4720         Glib::Threads::RWLock::WriterLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
4721         assert (!lm.locked ());
4722 #endif
4723
4724         if (!_main_outs) {
4725                 /* too early to be doing this stuff */
4726                 return;
4727         }
4728
4729         /* we'll build this new list here and then use it
4730          *
4731          * TODO put the ProcessorList is on the stack for RT-safety.
4732          */
4733
4734         ProcessorList new_processors;
4735         ProcessorList foldback_sends;
4736         ProcessorList::iterator dr;
4737         ProcessorList::iterator dw;
4738
4739         /* find visible processors */
4740
4741         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4742                 boost::shared_ptr<Send> auxsnd = boost::dynamic_pointer_cast<Send> ((*i));
4743                 if ((*i)->display_to_user ()) {
4744                         new_processors.push_back (*i);
4745                 }
4746                 else if (auxsnd && auxsnd->is_foldback ()) {
4747                         foldback_sends.push_back (*i);
4748                 }
4749         }
4750
4751         /* find the amp */
4752
4753         ProcessorList::iterator amp = find (new_processors.begin(), new_processors.end(), _amp);
4754
4755         if (amp == new_processors.end ()) {
4756                 error << string_compose (_("Amp/Fader on Route '%1' went AWOL. Re-added."), name()) << endmsg;
4757                 new_processors.push_front (_amp);
4758                 amp = find (new_processors.begin(), new_processors.end(), _amp);
4759         }
4760
4761         /* and the processor after the amp */
4762
4763         ProcessorList::iterator after_amp = amp;
4764         ++after_amp;
4765
4766         /* Pre-fader METER */
4767
4768         if (_meter && _meter_point == MeterPreFader) {
4769                 /* add meter just before the fader */
4770                 assert (!_meter->display_to_user ());
4771                 new_processors.insert (amp, _meter);
4772         }
4773
4774         /* MAIN OUTS */
4775
4776         assert (_main_outs);
4777         assert (!_main_outs->display_to_user ());
4778         new_processors.push_back (_main_outs);
4779
4780         /* iterator for the main outs */
4781
4782         ProcessorList::iterator main = new_processors.end();
4783         --main;
4784
4785         /* OUTPUT METERING */
4786
4787         if (_meter && (_meter_point == MeterOutput || _meter_point == MeterPostFader)) {
4788                 assert (!_meter->display_to_user ());
4789
4790                 /* add the processor just before or just after the main outs */
4791
4792                 ProcessorList::iterator meter_point = main;
4793
4794                 if (_meter_point == MeterOutput) {
4795                         ++meter_point;
4796                 }
4797                 new_processors.insert (meter_point, _meter);
4798         }
4799
4800         /* Foldback Sends */
4801
4802         for (ProcessorList::iterator i = foldback_sends.begin(); i != foldback_sends.end(); ++i) {
4803                 new_processors.insert (amp, (*i));
4804         }
4805
4806         /* MONITOR SEND */
4807
4808         if (_monitor_send && !is_monitor ()) {
4809                 assert (!_monitor_send->display_to_user ());
4810                 switch (Config->get_listen_position ()) {
4811                 case PreFaderListen:
4812                         switch (Config->get_pfl_position ()) {
4813                         case PFLFromBeforeProcessors:
4814                                 new_processors.push_front (_monitor_send);
4815                                 break;
4816                         case PFLFromAfterProcessors:
4817                                 new_processors.insert (amp, _monitor_send);
4818                                 break;
4819                         }
4820                         _monitor_send->set_can_pan (false);
4821                         break;
4822                 case AfterFaderListen:
4823                         switch (Config->get_afl_position ()) {
4824                         case AFLFromBeforeProcessors:
4825                                 new_processors.insert (after_amp, _monitor_send);
4826                                 break;
4827                         case AFLFromAfterProcessors:
4828                                 new_processors.insert (new_processors.end(), _monitor_send);
4829                                 break;
4830                         }
4831                         _monitor_send->set_can_pan (true);
4832                         break;
4833                 }
4834         }
4835
4836         /* MONITOR CONTROL */
4837
4838         if (_monitor_control && is_monitor ()) {
4839                 assert (!_monitor_control->display_to_user ());
4840                 new_processors.insert (amp, _monitor_control);
4841         }
4842
4843         /* TRIM CONTROL */
4844
4845         ProcessorList::iterator trim = new_processors.end();
4846
4847         if (_trim->active()) {
4848                 assert (!_trim->display_to_user ());
4849                 new_processors.push_front (_trim);
4850                 trim = new_processors.begin();
4851         }
4852
4853         /* INTERNAL RETURN */
4854
4855         /* doing this here means that any monitor control will come after
4856            the return and trim.
4857         */
4858
4859         if (_intreturn) {
4860                 assert (!_intreturn->display_to_user ());
4861                 new_processors.push_front (_intreturn);
4862         }
4863
4864         /* DISK READER & WRITER (for Track objects) */
4865
4866         if (_disk_reader || _disk_writer) {
4867                 switch (_disk_io_point) {
4868                 case DiskIOPreFader:
4869                         if (trim != new_processors.end()) {
4870                                 /* insert BEFORE TRIM */
4871                                 if (_disk_writer) {
4872                                         new_processors.insert (trim, _disk_writer);
4873                                 }
4874                                 if (_disk_reader) {
4875                                         new_processors.insert (trim, _disk_reader);
4876                                 }
4877                         } else {
4878                                 if (_disk_writer) {
4879                                         new_processors.push_front (_disk_writer);
4880                                 }
4881                                 if (_disk_reader) {
4882                                         new_processors.push_front (_disk_reader);
4883                                 }
4884                         }
4885                         break;
4886                 case DiskIOPostFader:
4887                         /* insert BEFORE main outs */
4888                         if (_disk_writer) {
4889                                 new_processors.insert (main, _disk_writer);
4890                         }
4891                         if (_disk_reader) {
4892                                 new_processors.insert (main, _disk_reader);
4893                         }
4894                         break;
4895                 case DiskIOCustom:
4896                         /* reader and writer are visible under this condition, so they
4897                          * are not invisible and thus not handled here.
4898                          */
4899                         break;
4900                 }
4901         }
4902
4903         /* ensure dist-writer is before disk-reader */
4904         if (_disk_reader && _disk_writer) {
4905                 ProcessorList::iterator reader_pos = find (new_processors.begin(), new_processors.end(), _disk_reader);
4906                 ProcessorList::iterator writer_pos = find (new_processors.begin(), new_processors.end(), _disk_writer);
4907                 assert (reader_pos != new_processors.end ());
4908                 assert (writer_pos != new_processors.end ());
4909                 if (std::distance (new_processors.begin(), reader_pos) < std::distance (new_processors.begin(), writer_pos)) {
4910                         new_processors.erase (reader_pos);
4911                         assert (writer_pos == find (new_processors.begin(), new_processors.end(), _disk_writer));
4912                         new_processors.insert (++writer_pos, _disk_reader);
4913                 }
4914         }
4915
4916         /* EXPORT PROCESSOR */
4917         if (_capturing_processor) {
4918                 assert (!_capturing_processor->display_to_user ());
4919                 ProcessorList::iterator reader_pos = find (new_processors.begin(), new_processors.end(), _disk_reader);
4920                 if (reader_pos != new_processors.end()) {
4921                         /* insert after disk-reader */
4922                         new_processors.insert (++reader_pos, _capturing_processor);
4923                 } else {
4924                         ProcessorList::iterator return_pos = find (new_processors.begin(), new_processors.end(), _intreturn);
4925                         /* insert after return */
4926                         if (return_pos != new_processors.end()) {
4927                                 new_processors.insert (++return_pos, _capturing_processor);
4928                         } else {
4929                                 new_processors.push_front (_capturing_processor);
4930                         }
4931                 }
4932         }
4933
4934         /* Polarity Invert */
4935         if (_polarity) {
4936                 ProcessorList::iterator reader_pos = find (new_processors.begin(), new_processors.end(), _disk_reader);
4937                 if (reader_pos != new_processors.end()) {
4938                         /* insert after disk-reader */
4939                         new_processors.insert (++reader_pos, _polarity);
4940                 } else {
4941                         ProcessorList::iterator return_pos = find (new_processors.begin(), new_processors.end(), _intreturn);
4942                         /* insert after return */
4943                         if (return_pos != new_processors.end()) {
4944                                 new_processors.insert (++return_pos, _polarity);
4945                         } else {
4946                                 new_processors.push_front (_polarity);
4947                         }
4948                 }
4949         }
4950
4951         /* Input meter */
4952         if (_meter && _meter_point == MeterInput) {
4953                 /* add meter just before the disk-writer (if any)
4954                  * otherwise at the top, but after the latency delayline
4955                  * (perhaps it should also be after intreturn on busses ??)
4956                  */
4957                 assert (!_meter->display_to_user ());
4958                 ProcessorList::iterator writer_pos = find (new_processors.begin(), new_processors.end(), _disk_writer);
4959                 if (writer_pos != new_processors.end()) {
4960                         /* insert before disk-writer */
4961                         new_processors.insert (writer_pos, _meter);
4962                 } else {
4963                         ProcessorList::iterator return_pos = find (new_processors.begin(), new_processors.end(), _intreturn);
4964                         /* insert after return */
4965                         if (return_pos != new_processors.end()) {
4966                                 new_processors.insert (++return_pos, _meter);
4967                         } else {
4968                                 new_processors.push_front (_meter);
4969                         }
4970                 }
4971         }
4972
4973         if (!is_master() && !is_monitor() && !is_auditioner()) {
4974                 ProcessorList::iterator reader_pos = find (new_processors.begin(), new_processors.end(), _disk_reader);
4975                 if (reader_pos != new_processors.end()) {
4976                         /* insert before disk-reader */
4977                         new_processors.insert (reader_pos, _delayline);
4978                 } else {
4979                         new_processors.push_front (_delayline);
4980                 }
4981         }
4982
4983         _processors = new_processors;
4984
4985         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4986                 if (!(*i)->display_to_user () && !(*i)->enabled () && (*i) != _monitor_send) {
4987                         (*i)->enable (true);
4988                 }
4989         }
4990
4991         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: setup_invisible_processors\n", _name));
4992         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4993                 DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1\n", (*i)->name ()));
4994         }
4995 }
4996
4997 void
4998 Route::unpan ()
4999 {
5000         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
5001         Glib::Threads::RWLock::ReaderLock lp (_processor_lock);
5002
5003         _pannable.reset ();
5004
5005         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5006                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery>(*i);
5007                 if (d) {
5008                         d->unpan ();
5009                 }
5010         }
5011 }
5012
5013 /** If the meter point is `Custom', make a note of where the meter is.
5014  *  This is so that if the meter point is subsequently set to something else,
5015  *  and then back to custom, we can put the meter back where it was last time
5016  *  custom was enabled.
5017  *
5018  *  Must be called with the _processor_lock held.
5019  */
5020 void
5021 Route::maybe_note_meter_position ()
5022 {
5023         if (_meter_point != MeterCustom) {
5024                 return;
5025         }
5026
5027         _custom_meter_position_noted = true;
5028         /* custom meter points range from after trim to before panner/main_outs
5029          * this is a limitation by the current processor UI
5030          */
5031         bool seen_trim = false;
5032         _processor_after_last_custom_meter.reset();
5033         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5034                 if ((*i) == _trim) {
5035                         seen_trim = true;
5036                 }
5037                 if ((*i) == _main_outs) {
5038                         _processor_after_last_custom_meter = *i;
5039                         break;
5040                 }
5041                 if (boost::dynamic_pointer_cast<PeakMeter> (*i)) {
5042                         if (!seen_trim) {
5043                                 _processor_after_last_custom_meter = _trim;
5044                         } else {
5045                                 ProcessorList::iterator j = i;
5046                                 ++j;
5047                                 assert(j != _processors.end ()); // main_outs should be before
5048                                 _processor_after_last_custom_meter = *j;
5049                         }
5050                         break;
5051                 }
5052         }
5053         assert(_processor_after_last_custom_meter.lock());
5054 }
5055
5056 boost::shared_ptr<Processor>
5057 Route::processor_by_id (PBD::ID id) const
5058 {
5059         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5060         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5061                 if ((*i)->id() == id) {
5062                         return *i;
5063                 }
5064         }
5065
5066         return boost::shared_ptr<Processor> ();
5067 }
5068
5069 /** @return what we should be metering; either the data coming from the input
5070  *  IO or the data that is flowing through the route.
5071  */
5072 MeterState
5073 Route::metering_state () const
5074 {
5075         return MeteringRoute;
5076 }
5077
5078 bool
5079 Route::has_external_redirects () const
5080 {
5081         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5082
5083                 /* ignore inactive processors and obviously ignore the main
5084                  * outs since everything has them and we don't care.
5085                  */
5086
5087                 if ((*i)->active() && (*i) != _main_outs && (*i)->does_routing()) {
5088                         return true;;
5089                 }
5090         }
5091
5092         return false;
5093 }
5094
5095 boost::shared_ptr<Processor>
5096 Route::the_instrument () const
5097 {
5098         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5099         return the_instrument_unlocked ();
5100 }
5101
5102 boost::shared_ptr<Processor>
5103 Route::the_instrument_unlocked () const
5104 {
5105         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5106                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*i);
5107                 if (pi && pi->plugin ()->get_info ()->is_instrument ()) {
5108                         return (*i);
5109                 }
5110         }
5111         return boost::shared_ptr<Processor>();
5112 }
5113
5114 bool
5115 Route::is_track()
5116 {
5117         return dynamic_cast<Track*>(this) != 0;
5118 }
5119
5120 void
5121 Route::non_realtime_locate (samplepos_t pos)
5122 {
5123         Automatable::non_realtime_locate (pos);
5124
5125         if (_pannable) {
5126                 _pannable->non_realtime_locate (pos);
5127         }
5128
5129 #if 0 // XXX mayhaps clear delayline here (and at stop?)
5130         if (_delayline) {
5131                 _delayline->flush ();
5132         }
5133 #endif
5134
5135         {
5136                 //Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
5137                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5138
5139                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5140                         (*i)->non_realtime_locate (pos);
5141                 }
5142         }
5143 }
5144
5145 void
5146 Route::fill_buffers_with_input (BufferSet& bufs, boost::shared_ptr<IO> io, pframes_t nframes)
5147 {
5148         size_t n_buffers;
5149         size_t i;
5150
5151         /* MIDI
5152          *
5153          * We don't currently mix MIDI input together, so we don't need the
5154          * complex logic of the audio case.
5155          */
5156
5157         n_buffers = bufs.count().n_midi ();
5158
5159         for (i = 0; i < n_buffers; ++i) {
5160
5161                 boost::shared_ptr<MidiPort> source_port = io->midi (i);
5162                 MidiBuffer& buf (bufs.get_midi (i));
5163
5164                 if (source_port) {
5165                         buf.copy (source_port->get_midi_buffer(nframes));
5166                 } else {
5167                         buf.silence (nframes);
5168                 }
5169         }
5170
5171         /* AUDIO */
5172
5173         n_buffers = bufs.count().n_audio();
5174
5175         size_t n_ports = io->n_ports().n_audio();
5176         float scaling = 1.0f;
5177
5178         if (n_ports > n_buffers) {
5179                 scaling = ((float) n_buffers) / n_ports;
5180         }
5181
5182         for (i = 0; i < n_ports; ++i) {
5183
5184                 /* if there are more ports than buffers, map them onto buffers
5185                  * in a round-robin fashion
5186                  */
5187
5188                 boost::shared_ptr<AudioPort> source_port = io->audio (i);
5189                 AudioBuffer& buf (bufs.get_audio (i%n_buffers));
5190
5191                 if (i < n_buffers) {
5192
5193                         /* first time through just copy a channel into
5194                            the output buffer.
5195                         */
5196
5197                         buf.read_from (source_port->get_audio_buffer (nframes), nframes);
5198
5199                         if (scaling != 1.0f) {
5200                                 buf.apply_gain (scaling, nframes);
5201                         }
5202
5203                 } else {
5204
5205                         /* on subsequent times around, merge data from
5206                          * the port with what is already there
5207                          */
5208
5209                         if (scaling != 1.0f) {
5210                                 buf.accumulate_with_gain_from (source_port->get_audio_buffer (nframes), nframes, 0, scaling);
5211                         } else {
5212                                 buf.accumulate_from (source_port->get_audio_buffer (nframes), nframes);
5213                         }
5214                 }
5215         }
5216
5217         /* silence any remaining buffers */
5218
5219         for (; i < n_buffers; ++i) {
5220                 AudioBuffer& buf (bufs.get_audio (i));
5221                 buf.silence (nframes);
5222         }
5223
5224         /* establish the initial setup of the buffer set, reflecting what was
5225            copied into it. unless, of course, we are the auditioner, in which
5226            case nothing was fed into it from the inputs at all.
5227         */
5228
5229         if (!is_auditioner()) {
5230                 bufs.set_count (io->n_ports());
5231         }
5232 }
5233
5234 boost::shared_ptr<AutomationControl>
5235 Route::pan_azimuth_control() const
5236 {
5237 #ifdef MIXBUS
5238 # undef MIXBUS_PORTS_H
5239 # include "../../gtk2_ardour/mixbus_ports.h"
5240         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5241         if (!plug) {
5242                 return boost::shared_ptr<AutomationControl>();
5243         }
5244         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_channel_post_pan)));
5245 #else
5246         if (!_pannable || !panner()) {
5247                 return boost::shared_ptr<AutomationControl>();
5248         }
5249         return _pannable->pan_azimuth_control;
5250 #endif
5251 }
5252
5253 boost::shared_ptr<AutomationControl>
5254 Route::pan_elevation_control() const
5255 {
5256         if (Profile->get_mixbus() || !_pannable || !panner()) {
5257                 return boost::shared_ptr<AutomationControl>();
5258         }
5259
5260         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5261
5262         if (c.find (PanElevationAutomation) != c.end()) {
5263                 return _pannable->pan_elevation_control;
5264         } else {
5265                 return boost::shared_ptr<AutomationControl>();
5266         }
5267 }
5268 boost::shared_ptr<AutomationControl>
5269 Route::pan_width_control() const
5270 {
5271 #ifdef MIXBUS
5272         if (mixbus() && _ch_pre) {
5273                 //mono blend
5274                 return boost::dynamic_pointer_cast<ARDOUR::AutomationControl>(_ch_pre->control(Evoral::Parameter(PluginAutomation, 0, 5)));
5275         }
5276 #endif
5277         if (Profile->get_mixbus() || !_pannable || !panner()) {
5278                 return boost::shared_ptr<AutomationControl>();
5279         }
5280
5281         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5282
5283         if (c.find (PanWidthAutomation) != c.end()) {
5284                 return _pannable->pan_width_control;
5285         } else {
5286                 return boost::shared_ptr<AutomationControl>();
5287         }
5288 }
5289 boost::shared_ptr<AutomationControl>
5290 Route::pan_frontback_control() const
5291 {
5292         if (Profile->get_mixbus() || !_pannable || !panner()) {
5293                 return boost::shared_ptr<AutomationControl>();
5294         }
5295
5296         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5297
5298         if (c.find (PanFrontBackAutomation) != c.end()) {
5299                 return _pannable->pan_frontback_control;
5300         } else {
5301                 return boost::shared_ptr<AutomationControl>();
5302         }
5303 }
5304 boost::shared_ptr<AutomationControl>
5305 Route::pan_lfe_control() const
5306 {
5307         if (Profile->get_mixbus() || !_pannable || !panner()) {
5308                 return boost::shared_ptr<AutomationControl>();
5309         }
5310
5311         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5312
5313         if (c.find (PanLFEAutomation) != c.end()) {
5314                 return _pannable->pan_lfe_control;
5315         } else {
5316                 return boost::shared_ptr<AutomationControl>();
5317         }
5318 }
5319
5320 uint32_t
5321 Route::eq_band_cnt () const
5322 {
5323         if (Profile->get_mixbus()) {
5324 #ifdef MIXBUS32C
5325                 if (is_master() || mixbus()) {
5326                         return 3;
5327                 } else {
5328                         return 4;
5329                 }
5330 #else
5331                 return 3;
5332 #endif
5333         } else {
5334                 /* Ardour has no well-known EQ object */
5335                 return 0;
5336         }
5337 }
5338
5339 boost::shared_ptr<AutomationControl>
5340 Route::eq_gain_controllable (uint32_t band) const
5341 {
5342 #ifdef MIXBUS
5343         boost::shared_ptr<PluginInsert> eq = ch_eq();
5344
5345         if (!eq) {
5346                 return boost::shared_ptr<AutomationControl>();
5347         }
5348
5349         uint32_t port_number;
5350         if (is_master() || mixbus()) {
5351                 switch (band) {
5352                         case 0: port_number = 4; break;
5353                         case 1: port_number = 3; break;
5354                         case 2: port_number = 2; break;
5355                         default:
5356                                 return boost::shared_ptr<AutomationControl>();
5357                 }
5358         } else {
5359 #ifdef MIXBUS32C
5360                 switch (band) {
5361                         case 0: port_number = 14; break;
5362                         case 1: port_number = 12; break;
5363                         case 2: port_number = 10; break;
5364                         case 3: port_number =  8; break;
5365                         default:
5366                                 return boost::shared_ptr<AutomationControl>();
5367                 }
5368 #else
5369                 switch (band) {
5370                         case 0: port_number = 8; break;
5371                         case 1: port_number = 6; break;
5372                         case 2: port_number = 4; break;
5373                         default:
5374                                 return boost::shared_ptr<AutomationControl>();
5375                 }
5376 #endif
5377         }
5378
5379         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_number)));
5380 #else
5381         return boost::shared_ptr<AutomationControl>();
5382 #endif
5383 }
5384 boost::shared_ptr<AutomationControl>
5385 Route::eq_freq_controllable (uint32_t band) const
5386 {
5387 #ifdef MIXBUS
5388         if (mixbus() || is_master()) {
5389                 /* no frequency controls for mixbusses or master */
5390                 return boost::shared_ptr<AutomationControl>();
5391         }
5392
5393         boost::shared_ptr<PluginInsert> eq = ch_eq();
5394
5395         if (!eq) {
5396                 return boost::shared_ptr<AutomationControl>();
5397         }
5398
5399         uint32_t port_number;
5400 #ifdef MIXBUS32C
5401         switch (band) {
5402                 case 0: port_number = 13; break; // lo
5403                 case 1: port_number = 11; break; // lo mid
5404                 case 2: port_number = 9; break; // hi mid
5405                 case 3: port_number = 7; break; // hi
5406                 default:
5407                         return boost::shared_ptr<AutomationControl>();
5408         }
5409 #else
5410         switch (band) {
5411                 case 0: port_number = 7; break;
5412                 case 1: port_number = 5; break;
5413                 case 2: port_number = 3; break;
5414                 default:
5415                         return boost::shared_ptr<AutomationControl>();
5416         }
5417 #endif
5418
5419         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_number)));
5420 #else
5421         return boost::shared_ptr<AutomationControl>();
5422 #endif
5423 }
5424
5425 boost::shared_ptr<AutomationControl>
5426 Route::eq_q_controllable (uint32_t band) const
5427 {
5428         return boost::shared_ptr<AutomationControl>();
5429 }
5430
5431 boost::shared_ptr<AutomationControl>
5432 Route::eq_shape_controllable (uint32_t band) const
5433 {
5434 #ifdef MIXBUS32C
5435         boost::shared_ptr<PluginInsert> eq = ch_eq();
5436         if (is_master() || mixbus() || !eq) {
5437                 return boost::shared_ptr<AutomationControl>();
5438         }
5439         switch (band) {
5440                 case 0:
5441                         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 4))); // lo bell
5442                         break;
5443                 case 3:
5444                         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 3))); // hi bell
5445                         break;
5446                 default:
5447                         break;
5448         }
5449 #endif
5450         return boost::shared_ptr<AutomationControl>();
5451 }
5452
5453 boost::shared_ptr<AutomationControl>
5454 Route::eq_enable_controllable () const
5455 {
5456 #ifdef MIXBUS
5457         boost::shared_ptr<PluginInsert> eq = ch_eq();
5458
5459         if (!eq) {
5460                 return boost::shared_ptr<AutomationControl>();
5461         }
5462
5463         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 1)));
5464 #else
5465         return boost::shared_ptr<AutomationControl>();
5466 #endif
5467 }
5468
5469 boost::shared_ptr<AutomationControl>
5470 Route::filter_freq_controllable (bool hpf) const
5471 {
5472 #ifdef MIXBUS
5473         boost::shared_ptr<PluginInsert> eq = ch_eq();
5474
5475         if (is_master() || mixbus() || !eq) {
5476                 return boost::shared_ptr<AutomationControl>();
5477         }
5478         if (hpf) {
5479 #ifdef MIXBUS32C
5480                 return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 5))); // HPF freq
5481 #else
5482                 return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 2)));
5483 #endif
5484         } else {
5485 #ifdef MIXBUS32C
5486                 return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 6))); // LPF freq
5487 #else
5488                 return boost::shared_ptr<AutomationControl>();
5489 #endif
5490         }
5491
5492 #else
5493         return boost::shared_ptr<AutomationControl>();
5494 #endif
5495 }
5496
5497 boost::shared_ptr<AutomationControl>
5498 Route::filter_slope_controllable (bool) const
5499 {
5500         return boost::shared_ptr<AutomationControl>();
5501 }
5502
5503 boost::shared_ptr<AutomationControl>
5504 Route::filter_enable_controllable (bool) const
5505 {
5506 #ifdef MIXBUS32C
5507         boost::shared_ptr<PluginInsert> eq = ch_eq();
5508
5509         if (is_master() || mixbus() || !eq) {
5510                 return boost::shared_ptr<AutomationControl>();
5511         }
5512
5513         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 2)));
5514 #else
5515         return boost::shared_ptr<AutomationControl>();
5516 #endif
5517 }
5518
5519 boost::shared_ptr<AutomationControl>
5520 Route::tape_drive_controllable () const
5521 {
5522 #ifdef MIXBUS
5523         if (_ch_pre && mixbus()) {
5524                 return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (_ch_pre->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 4)));
5525         }
5526         if (_ch_pre && is_master()) {
5527                 return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (_ch_pre->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 1)));
5528         }
5529 #endif
5530
5531         return boost::shared_ptr<AutomationControl>();
5532 }
5533
5534 string
5535 Route::eq_band_name (uint32_t band) const
5536 {
5537 #ifdef MIXBUS32C
5538         if (is_master() || mixbus()) {
5539 #endif
5540         if (Profile->get_mixbus()) {
5541                 switch (band) {
5542                         case 0: return _("lo");
5543                         case 1: return _("mid");
5544                         case 2: return _("hi");
5545                         default: return string();
5546                 }
5547         } else {
5548                 return string ();
5549         }
5550 #ifdef MIXBUS32C
5551         } else {
5552                 switch (band) {
5553                         case 0: return _("lo");
5554                         case 1: return _("lo mid");
5555                         case 2: return _("hi mid");
5556                         case 3: return _("hi");
5557                         default: return string();
5558                 }
5559         }
5560 #endif
5561 }
5562
5563 boost::shared_ptr<AutomationControl>
5564 Route::comp_enable_controllable () const
5565 {
5566 #ifdef MIXBUS
5567         boost::shared_ptr<PluginInsert> comp = ch_comp();
5568
5569         if (!comp) {
5570                 return boost::shared_ptr<AutomationControl>();
5571         }
5572
5573         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 1)));
5574 #else
5575         return boost::shared_ptr<AutomationControl>();
5576 #endif
5577 }
5578 boost::shared_ptr<AutomationControl>
5579 Route::comp_threshold_controllable () const
5580 {
5581 #ifdef MIXBUS
5582         boost::shared_ptr<PluginInsert> comp = ch_comp();
5583
5584         if (!comp) {
5585                 return boost::shared_ptr<AutomationControl>();
5586         }
5587
5588         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 2)));
5589
5590 #else
5591         return boost::shared_ptr<AutomationControl>();
5592 #endif
5593 }
5594 boost::shared_ptr<AutomationControl>
5595 Route::comp_speed_controllable () const
5596 {
5597 #ifdef MIXBUS
5598         boost::shared_ptr<PluginInsert> comp = ch_comp();
5599
5600         if (!comp) {
5601                 return boost::shared_ptr<AutomationControl>();
5602         }
5603
5604         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 3)));
5605 #else
5606         return boost::shared_ptr<AutomationControl>();
5607 #endif
5608 }
5609 boost::shared_ptr<AutomationControl>
5610 Route::comp_mode_controllable () const
5611 {
5612 #ifdef MIXBUS
5613         boost::shared_ptr<PluginInsert> comp = ch_comp();
5614
5615         if (!comp) {
5616                 return boost::shared_ptr<AutomationControl>();
5617         }
5618
5619         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 4)));
5620 #else
5621         return boost::shared_ptr<AutomationControl>();
5622 #endif
5623 }
5624 boost::shared_ptr<AutomationControl>
5625 Route::comp_makeup_controllable () const
5626 {
5627 #ifdef MIXBUS
5628         boost::shared_ptr<PluginInsert> comp = ch_comp();
5629
5630         if (!comp) {
5631                 return boost::shared_ptr<AutomationControl>();
5632         }
5633
5634         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 5)));
5635 #else
5636         return boost::shared_ptr<AutomationControl>();
5637 #endif
5638 }
5639 boost::shared_ptr<ReadOnlyControl>
5640 Route::comp_redux_controllable () const
5641 {
5642 #ifdef MIXBUS
5643         boost::shared_ptr<PluginInsert> comp = ch_comp();
5644
5645         if (!comp) {
5646                 return boost::shared_ptr<ReadOnlyControl>();
5647         }
5648         if (is_master()) {
5649                 return comp->control_output (2);
5650         } else {
5651                 return comp->control_output (6);
5652         }
5653
5654 #else
5655         return boost::shared_ptr<ReadOnlyControl>();
5656 #endif
5657 }
5658
5659 string
5660 Route::comp_mode_name (uint32_t mode) const
5661 {
5662 #ifdef MIXBUS
5663         switch (mode) {
5664         case 0:
5665                 return _("Leveler");
5666         case 1:
5667                 return _("Compressor");
5668         case 2:
5669                 return _("Limiter");
5670         case 3:
5671                 return mixbus() ? _("Sidechain") : _("Limiter");
5672         }
5673
5674         return _("???");
5675 #else
5676         return _("???");
5677 #endif
5678 }
5679
5680 string
5681 Route::comp_speed_name (uint32_t mode) const
5682 {
5683 #ifdef MIXBUS
5684         switch (mode) {
5685         case 0:
5686                 return _("Attk");
5687         case 1:
5688                 return _("Ratio");
5689         case 2:
5690         case 3:
5691                 return _("Rels");
5692         }
5693         return _("???");
5694 #else
5695         return _("???");
5696 #endif
5697 }
5698
5699 boost::shared_ptr<AutomationControl>
5700 Route::send_pan_azi_controllable (uint32_t n) const
5701 {
5702 #ifdef  MIXBUS
5703 # undef MIXBUS_PORTS_H
5704 # include "../../gtk2_ardour/mixbus_ports.h"
5705         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5706         if (plug && !mixbus()) {
5707                 uint32_t port_id = 0;
5708                 switch (n) {
5709 # ifdef MIXBUS32C
5710                         case  0: port_id = port_channel_post_aux0_pan; break;  //32c mb "pan" controls use zero-based names, unlike levels. ugh
5711                         case  1: port_id = port_channel_post_aux1_pan; break;
5712                         case  2: port_id = port_channel_post_aux2_pan; break;
5713                         case  3: port_id = port_channel_post_aux3_pan; break;
5714                         case  4: port_id = port_channel_post_aux4_pan; break;
5715                         case  5: port_id = port_channel_post_aux5_pan; break;
5716                         case  6: port_id = port_channel_post_aux6_pan; break;
5717                         case  7: port_id = port_channel_post_aux7_pan; break;
5718                         case  8: port_id = port_channel_post_aux8_pan; break;
5719                         case  9: port_id = port_channel_post_aux9_pan; break;
5720                         case 10: port_id = port_channel_post_aux10_pan; break;
5721                         case 11: port_id = port_channel_post_aux11_pan; break;
5722 # endif
5723                         default:
5724                                 break;
5725                 }
5726
5727                 if (port_id > 0) {
5728                         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_id)));
5729                 }
5730         }
5731 #endif
5732
5733         return boost::shared_ptr<AutomationControl>();
5734 }
5735
5736 boost::shared_ptr<AutomationControl>
5737 Route::send_level_controllable (uint32_t n) const
5738 {
5739 #ifdef  MIXBUS
5740 # undef MIXBUS_PORTS_H
5741 # include "../../gtk2_ardour/mixbus_ports.h"
5742         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5743         if (plug && !mixbus()) {
5744                 uint32_t port_id = 0;
5745                 switch (n) {
5746                         case  0: port_id = port_channel_post_aux1_level; break;
5747                         case  1: port_id = port_channel_post_aux2_level; break;
5748                         case  2: port_id = port_channel_post_aux3_level; break;
5749                         case  3: port_id = port_channel_post_aux4_level; break;
5750                         case  4: port_id = port_channel_post_aux5_level; break;
5751                         case  5: port_id = port_channel_post_aux6_level; break;
5752                         case  6: port_id = port_channel_post_aux7_level; break;
5753                         case  7: port_id = port_channel_post_aux8_level; break;
5754 # ifdef MIXBUS32C
5755                         case  8: port_id = port_channel_post_aux9_level; break;
5756                         case  9: port_id = port_channel_post_aux10_level; break;
5757                         case 10: port_id = port_channel_post_aux11_level; break;
5758                         case 11: port_id = port_channel_post_aux12_level; break;
5759 # endif
5760                         default:
5761                                 break;
5762                 }
5763
5764                 if (port_id > 0) {
5765                         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_id)));
5766                 }
5767 # ifdef MIXBUS32C
5768                 assert (n > 11);
5769                 n -= 12;
5770 # else
5771                 assert (n > 7);
5772                 n -= 8;
5773 # endif
5774         }
5775 #endif
5776         boost::shared_ptr<Send> s = boost::dynamic_pointer_cast<Send>(nth_send (n));
5777         if (!s) {
5778                 return boost::shared_ptr<AutomationControl>();
5779         }
5780         return s->gain_control ();
5781 }
5782
5783 boost::shared_ptr<AutomationControl>
5784 Route::send_enable_controllable (uint32_t n) const
5785 {
5786 #ifdef  MIXBUS
5787 # undef MIXBUS_PORTS_H
5788 # include "../../gtk2_ardour/mixbus_ports.h"
5789         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5790         if (plug && !mixbus()) {
5791                 uint32_t port_id = 0;
5792                 switch (n) {
5793                         case  0: port_id = port_channel_post_aux1_asgn; break;
5794                         case  1: port_id = port_channel_post_aux2_asgn; break;
5795                         case  2: port_id = port_channel_post_aux3_asgn; break;
5796                         case  3: port_id = port_channel_post_aux4_asgn; break;
5797                         case  4: port_id = port_channel_post_aux5_asgn; break;
5798                         case  5: port_id = port_channel_post_aux6_asgn; break;
5799                         case  6: port_id = port_channel_post_aux7_asgn; break;
5800                         case  7: port_id = port_channel_post_aux8_asgn; break;
5801 # ifdef MIXBUS32C
5802                         case  8: port_id = port_channel_post_aux9_asgn; break;
5803                         case  9: port_id = port_channel_post_aux10_asgn; break;
5804                         case 10: port_id = port_channel_post_aux11_asgn; break;
5805                         case 11: port_id = port_channel_post_aux12_asgn; break;
5806 # endif
5807                         default:
5808                                 break;
5809                 }
5810
5811                 if (port_id > 0) {
5812                         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_id)));
5813                 }
5814 # ifdef MIXBUS32C
5815                 assert (n > 11);
5816                 n -= 12;
5817 # else
5818                 assert (n > 7);
5819                 n -= 8;
5820 # endif
5821         }
5822 #endif
5823         /* although Ardour sends have enable/disable as part of the Processor
5824          * API, it is not exposed as a controllable.
5825          *
5826          * XXX: we should fix this (make it click-free, automatable enable-control)
5827          */
5828         return boost::shared_ptr<AutomationControl>();
5829 }
5830
5831 string
5832 Route::send_name (uint32_t n) const
5833 {
5834 #ifdef MIXBUS
5835         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5836         if (plug && !mixbus()) {
5837 # ifdef MIXBUS32C
5838                 if (n < 12) {
5839                         return _session.get_mixbus (n)->name();
5840                 }
5841                 n -= 12;
5842 #else
5843                 if (n < 8) {
5844                         return _session.get_mixbus (n)->name();
5845                 }
5846                 n -= 8;
5847 # endif
5848         }
5849 #endif
5850         boost::shared_ptr<Processor> p = nth_send (n);
5851         if (p) {
5852                 return p->name();
5853         } else {
5854                 return string();
5855         }
5856 }
5857
5858 boost::shared_ptr<AutomationControl>
5859 Route::master_send_enable_controllable () const
5860 {
5861 #ifdef  MIXBUS
5862         if (is_master() || is_monitor() || is_auditioner()) {
5863                 return boost::shared_ptr<AutomationControl>();
5864         }
5865
5866         boost::shared_ptr<ARDOUR::PluginInsert> plug = mixbus() ? ch_pre () : ch_post();
5867         if (!plug) {
5868                 return boost::shared_ptr<AutomationControl>();
5869         }
5870         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, mixbus() ? 3 : 19)));
5871 #else
5872         return boost::shared_ptr<AutomationControl>();
5873 #endif
5874 }
5875
5876 bool
5877 Route::slaved () const
5878 {
5879         if (!_gain_control) {
5880                 return false;
5881         }
5882         /* just test one particular control, not all of them */
5883         return _gain_control->slaved ();
5884 }
5885
5886 bool
5887 Route::slaved_to (boost::shared_ptr<VCA> vca) const
5888 {
5889         if (!vca || !_gain_control) {
5890                 return false;
5891         }
5892
5893         /* just test one particular control, not all of them */
5894
5895         return _gain_control->slaved_to (vca->gain_control());
5896 }
5897
5898 bool
5899 Route::muted_by_others_soloing () const
5900 {
5901         if (!can_be_muted_by_others ()) {
5902                 return false;
5903         }
5904
5905         return  _session.soloing() && !_solo_control->soloed() && !_solo_isolate_control->solo_isolated();
5906 }
5907
5908 void
5909 Route::clear_all_solo_state ()
5910 {
5911         _solo_control->clear_all_solo_state ();
5912 }
5913
5914 boost::shared_ptr<AutomationControl>
5915 Route::automation_control_recurse (PBD::ID const & id) const
5916 {
5917         boost::shared_ptr<AutomationControl> ac = Automatable::automation_control (id);
5918
5919         if (ac) {
5920                 return ac;
5921         }
5922
5923         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5924
5925         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5926                 if ((ac = (*i)->automation_control (id))) {
5927                         return ac;
5928                 }
5929         }
5930
5931         return boost::shared_ptr<AutomationControl> ();
5932 }
5933
5934 SlavableControlList
5935 Route::slavables () const
5936 {
5937         SlavableControlList rv;
5938         rv.push_back (_gain_control);
5939         rv.push_back (_mute_control);
5940         rv.push_back (_solo_control);
5941         return rv;
5942 }
5943
5944 void
5945 Route::set_disk_io_point (DiskIOPoint diop)
5946 {
5947         bool display = false;
5948
5949         cerr << "set disk io to " << enum_2_string (diop) << endl;
5950
5951         switch (diop) {
5952         case DiskIOCustom:
5953                 display = true;
5954                 break;
5955         default:
5956                 display = false;
5957         }
5958
5959         if (_disk_writer) {
5960                 _disk_writer->set_display_to_user (display);
5961         }
5962
5963         if (_disk_reader) {
5964                 _disk_reader->set_display_to_user (display);
5965         }
5966
5967         const bool changed = (diop != _disk_io_point);
5968
5969         _disk_io_point = diop;
5970
5971         if (changed) {
5972                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
5973                 configure_processors (0);
5974         }
5975
5976         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
5977 }
5978
5979 void
5980 Route::set_loop (Location* l)
5981 {
5982         _loop_location = l;
5983         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5984         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5985                 (*i)->set_loop (l);
5986         }
5987 }
5988
5989 #ifdef USE_TRACKS_CODE_FEATURES
5990
5991 /* This is the Tracks version of Track::monitoring_state().
5992  *
5993  * Ardour developers: try to flag or fix issues if parts of the libardour API
5994  * change in ways that invalidate this
5995  */
5996
5997 MonitorState
5998 Route::monitoring_state () const
5999 {
6000         /* Explicit requests */
6001
6002         if (_monitoring != MonitorInput) {
6003                 return MonitoringInput;
6004         }
6005
6006         if (_monitoring & MonitorDisk) {
6007                 return MonitoringDisk;
6008         }
6009
6010         /* This is an implementation of the truth table in doc/monitor_modes.pdf;
6011            I don't think it's ever going to be too pretty too look at.
6012         */
6013
6014         // GZ: NOT USED IN TRACKS
6015         //bool const auto_input = _session.config.get_auto_input ();
6016         //bool const software_monitor = Config->get_monitoring_model() == SoftwareMonitoring;
6017         //bool const tape_machine_mode = Config->get_tape_machine_mode ();
6018
6019         bool const roll = _session.transport_rolling ();
6020         bool const track_rec = _diskstream->record_enabled ();
6021         bool session_rec = _session.actively_recording ();
6022
6023         if (track_rec) {
6024
6025                 if (!session_rec && roll) {
6026                         return MonitoringDisk;
6027                 } else {
6028                         return MonitoringInput;
6029                 }
6030
6031         } else {
6032
6033                 if (roll) {
6034                         return MonitoringDisk;
6035                 }
6036         }
6037
6038         return MonitoringSilence;
6039 }
6040
6041 #else
6042
6043 /* This is the Ardour/Mixbus version of Track::monitoring_state().
6044  *
6045  * Tracks developers: do NOT modify this method under any circumstances.
6046  */
6047
6048 MonitorState
6049 Route::monitoring_state () const
6050 {
6051         if (!_disk_reader) {
6052                 return MonitoringInput;
6053         }
6054
6055         /* Explicit requests */
6056         MonitorChoice m (_monitoring_control->monitoring_choice());
6057
6058         if (m != MonitorAuto) {
6059
6060                 MonitorState ms ((MonitorState) 0);
6061
6062                 if (m & MonitorInput) {
6063                         ms = MonitoringInput;
6064                 }
6065
6066                 if (m & MonitorDisk) {
6067                         ms = MonitorState (ms | MonitoringDisk);
6068                 }
6069
6070                 return ms;
6071         }
6072
6073         switch (_session.config.get_session_monitoring ()) {
6074                 case MonitorDisk:
6075                         return MonitoringDisk;
6076                         break;
6077                 case MonitorInput:
6078                         return MonitoringInput;
6079                         break;
6080                 default:
6081                         break;
6082         }
6083
6084         return get_auto_monitoring_state();
6085 }
6086 #endif