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