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