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