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