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