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