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