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