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