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