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