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