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