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