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