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