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