3442d0ec8aca145c56c0bc774ec8f06bd1e4c3b5
[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         for (i = _processors.begin(); i != _processors.end(); ++i) {
2785                 if (!full_state) {
2786                         /* template save: do not include internal sends functioning as
2787                            aux sends because the chance of the target ID
2788                            in the session where this template is used
2789                            is not very likely.
2790
2791                            similarly, do not save listen sends which connect to
2792                            the monitor section, because these will always be
2793                            added if necessary.
2794                         */
2795                         boost::shared_ptr<InternalSend> is;
2796
2797                         if ((is = boost::dynamic_pointer_cast<InternalSend> (*i)) != 0) {
2798                                 if (is->role() == Delivery::Listen) {
2799                                         continue;
2800                                 }
2801                         }
2802                 }
2803                 node->add_child_nocopy((*i)->state (full_state));
2804         }
2805
2806         if (_extra_xml) {
2807                 node->add_child_copy (*_extra_xml);
2808         }
2809
2810         if (_custom_meter_position_noted) {
2811                 boost::shared_ptr<Processor> after = _processor_after_last_custom_meter.lock ();
2812                 if (after) {
2813                         after->id().print (buf, sizeof (buf));
2814                         node->add_property (X_("processor-after-last-custom-meter"), buf);
2815                 }
2816         }
2817
2818         if (!_session._template_state_dir.empty()) {
2819                 foreach_processor (sigc::bind (sigc::mem_fun (*this, &Route::set_plugin_state_dir), ""));
2820         }
2821
2822         return *node;
2823 }
2824
2825 int
2826 Route::set_state (const XMLNode& node, int version)
2827 {
2828         if (version < 3000) {
2829                 return set_state_2X (node, version);
2830         }
2831
2832         XMLNodeList nlist;
2833         XMLNodeConstIterator niter;
2834         XMLNode *child;
2835         XMLProperty const * prop;
2836
2837         if (node.name() != "Route"){
2838                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
2839                 return -1;
2840         }
2841
2842         if ((prop = node.property (X_("name"))) != 0) {
2843                 Route::set_name (prop->value());
2844         }
2845
2846         set_id (node);
2847         _initial_io_setup = true;
2848
2849         if ((prop = node.property (X_("flags"))) != 0) {
2850                 _flags = Flag (string_2_enum (prop->value(), _flags));
2851         } else {
2852                 _flags = Flag (0);
2853         }
2854
2855         if ((prop = node.property (X_("strict-io"))) != 0) {
2856                 _strict_io = string_is_affirmative (prop->value());
2857         }
2858
2859         if (is_master() || is_monitor() || is_auditioner()) {
2860                 _mute_master->set_solo_ignore (true);
2861         }
2862
2863         if (is_monitor()) {
2864                 /* monitor bus does not get a panner, but if (re)created
2865                    via XML, it will already have one by the time we
2866                    call ::set_state(). so ... remove it.
2867                 */
2868                 unpan ();
2869         }
2870
2871         /* add all processors (except amp, which is always present) */
2872
2873         nlist = node.children();
2874         XMLNode processor_state (X_("processor_state"));
2875
2876         Stateful::save_extra_xml (node);
2877
2878         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2879
2880                 child = *niter;
2881
2882                 if (child->name() == IO::state_node_name) {
2883                         if ((prop = child->property (X_("direction"))) == 0) {
2884                                 continue;
2885                         }
2886
2887                         if (prop->value() == "Input") {
2888                                 _input->set_state (*child, version);
2889                         } else if (prop->value() == "Output") {
2890                                 _output->set_state (*child, version);
2891                         }
2892                 }
2893
2894                 if (child->name() == X_("Processor")) {
2895                         processor_state.add_child_copy (*child);
2896                 }
2897
2898                 if (child->name() == X_("Pannable")) {
2899                         if (_pannable) {
2900                                 _pannable->set_state (*child, version);
2901                         } else {
2902                                 warning << string_compose (_("Pannable state found for route (%1) without a panner!"), name()) << endmsg;
2903                         }
2904                 }
2905         }
2906
2907         if ((prop = node.property (X_("meter-point"))) != 0) {
2908                 MeterPoint mp = MeterPoint (string_2_enum (prop->value (), _meter_point));
2909                 set_meter_point (mp, true);
2910                 if (_meter) {
2911                         _meter->set_display_to_user (_meter_point == MeterCustom);
2912                 }
2913         }
2914
2915         if ((prop = node.property (X_("meter-type"))) != 0) {
2916                 _meter_type = MeterType (string_2_enum (prop->value (), _meter_type));
2917         }
2918
2919         _initial_io_setup = false;
2920
2921         set_processor_state (processor_state);
2922
2923         // this looks up the internal instrument in processors
2924         reset_instrument_info();
2925
2926         if ((prop = node.property ("self-solo")) != 0) {
2927                 set_self_solo (string_is_affirmative (prop->value()));
2928         }
2929
2930         if ((prop = node.property ("soloed-by-upstream")) != 0) {
2931                 _soloed_by_others_upstream = 0; // needed for mod_.... () to work
2932                 mod_solo_by_others_upstream (atoi (prop->value()));
2933         }
2934
2935         if ((prop = node.property ("soloed-by-downstream")) != 0) {
2936                 _soloed_by_others_downstream = 0; // needed for mod_.... () to work
2937                 mod_solo_by_others_downstream (atoi (prop->value()));
2938         }
2939
2940         if ((prop = node.property ("solo-isolated")) != 0) {
2941                 set_solo_isolated (string_is_affirmative (prop->value()), Controllable::NoGroup);
2942         }
2943
2944         if ((prop = node.property ("solo-safe")) != 0) {
2945                 set_solo_safe (string_is_affirmative (prop->value()), Controllable::NoGroup);
2946         }
2947
2948         if ((prop = node.property (X_("phase-invert"))) != 0) {
2949                 set_phase_invert (boost::dynamic_bitset<> (prop->value ()));
2950         }
2951
2952         if ((prop = node.property (X_("denormal-protection"))) != 0) {
2953                 set_denormal_protection (string_is_affirmative (prop->value()));
2954         }
2955
2956         if ((prop = node.property (X_("active"))) != 0) {
2957                 bool yn = string_is_affirmative (prop->value());
2958                 set_active (yn, this);
2959         }
2960
2961         if ((prop = node.property (X_("order-key"))) != 0) { // New order key (no separate mixer/editor ordering)
2962                 set_order_key (atoi(prop->value()));
2963         }
2964
2965         if ((prop = node.property (X_("order-keys"))) != 0) { // Deprecated order keys
2966
2967                 int32_t n;
2968
2969                 string::size_type colon, equal;
2970                 string remaining = prop->value();
2971
2972                 while (remaining.length()) {
2973
2974                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
2975                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2976                                       << endmsg;
2977                         } else {
2978                                 if (sscanf (remaining.substr (equal+1).c_str(), "%d", &n) != 1) {
2979                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2980                                               << endmsg;
2981                                 } else {
2982                                         string keyname = remaining.substr (0, equal);
2983
2984                                         if ((keyname == "EditorSort") || (keyname == "editor")) {
2985                                                 cerr << "Setting " << name() << " order key to " << n << " using saved Editor order." << endl;
2986                                                 set_order_key (n);
2987                                         }
2988                                 }
2989                         }
2990
2991                         colon = remaining.find_first_of (':');
2992
2993                         if (colon != string::npos) {
2994                                 remaining = remaining.substr (colon+1);
2995                         } else {
2996                                 break;
2997                         }
2998                 }
2999         }
3000
3001         if ((prop = node.property (X_("processor-after-last-custom-meter"))) != 0) {
3002                 PBD::ID id (prop->value ());
3003                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3004                 ProcessorList::const_iterator i = _processors.begin ();
3005                 while (i != _processors.end() && (*i)->id() != id) {
3006                         ++i;
3007                 }
3008
3009                 if (i != _processors.end ()) {
3010                         _processor_after_last_custom_meter = *i;
3011                         _custom_meter_position_noted = true;
3012                 }
3013         }
3014
3015         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
3016                 child = *niter;
3017
3018                 if (child->name() == X_("Comment")) {
3019
3020                         /* XXX this is a terrible API design in libxml++ */
3021
3022                         XMLNode *cmt = *(child->children().begin());
3023                         _comment = cmt->content();
3024
3025                 } else if (child->name() == Controllable::xml_node_name && (prop = child->property("name")) != 0) {
3026                         if (prop->value() == "solo") {
3027                                 _solo_control->set_state (*child, version);
3028                         } else if (prop->value() == "mute") {
3029                                 _mute_control->set_state (*child, version);
3030                         }
3031
3032                 } else if (child->name() == X_("RemoteControl")) {
3033                         if ((prop = child->property (X_("id"))) != 0) {
3034                                 int32_t x;
3035                                 sscanf (prop->value().c_str(), "%d", &x);
3036                                 set_remote_control_id_internal (x);
3037                         }
3038
3039                 } else if (child->name() == X_("MuteMaster")) {
3040                         _mute_master->set_state (*child, version);
3041
3042                 } else if (child->name() == Automatable::xml_node_name) {
3043                         set_automation_xml_state (*child, Evoral::Parameter(NullAutomation));
3044                 }
3045         }
3046
3047         return 0;
3048 }
3049
3050 int
3051 Route::set_state_2X (const XMLNode& node, int version)
3052 {
3053         LocaleGuard lg;
3054         XMLNodeList nlist;
3055         XMLNodeConstIterator niter;
3056         XMLNode *child;
3057         XMLProperty const * prop;
3058
3059         /* 2X things which still remain to be handled:
3060          * default-type
3061          * automation
3062          * controlouts
3063          */
3064
3065         if (node.name() != "Route") {
3066                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
3067                 return -1;
3068         }
3069
3070         if ((prop = node.property (X_("flags"))) != 0) {
3071                 string f = prop->value ();
3072                 boost::replace_all (f, "ControlOut", "MonitorOut");
3073                 _flags = Flag (string_2_enum (f, _flags));
3074         } else {
3075                 _flags = Flag (0);
3076         }
3077
3078         if (is_master() || is_monitor() || is_auditioner()) {
3079                 _mute_master->set_solo_ignore (true);
3080         }
3081
3082         if ((prop = node.property (X_("phase-invert"))) != 0) {
3083                 boost::dynamic_bitset<> p (_input->n_ports().n_audio ());
3084                 if (string_is_affirmative (prop->value ())) {
3085                         p.set ();
3086                 }
3087                 set_phase_invert (p);
3088         }
3089
3090         if ((prop = node.property (X_("denormal-protection"))) != 0) {
3091                 set_denormal_protection (string_is_affirmative (prop->value()));
3092         }
3093
3094         if ((prop = node.property (X_("soloed"))) != 0) {
3095                 bool yn = string_is_affirmative (prop->value());
3096
3097                 /* XXX force reset of solo status */
3098
3099                 set_solo (yn);
3100         }
3101
3102         if ((prop = node.property (X_("muted"))) != 0) {
3103
3104                 bool first = true;
3105                 bool muted = string_is_affirmative (prop->value());
3106
3107                 if (muted) {
3108
3109                         string mute_point;
3110
3111                         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
3112
3113                                 if (string_is_affirmative (prop->value())){
3114                                         mute_point = mute_point + "PreFader";
3115                                         first = false;
3116                                 }
3117                         }
3118
3119                         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
3120
3121                                 if (string_is_affirmative (prop->value())){
3122
3123                                         if (!first) {
3124                                                 mute_point = mute_point + ",";
3125                                         }
3126
3127                                         mute_point = mute_point + "PostFader";
3128                                         first = false;
3129                                 }
3130                         }
3131
3132                         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
3133
3134                                 if (string_is_affirmative (prop->value())){
3135
3136                                         if (!first) {
3137                                                 mute_point = mute_point + ",";
3138                                         }
3139
3140                                         mute_point = mute_point + "Listen";
3141                                         first = false;
3142                                 }
3143                         }
3144
3145                         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
3146
3147                                 if (string_is_affirmative (prop->value())){
3148
3149                                         if (!first) {
3150                                                 mute_point = mute_point + ",";
3151                                         }
3152
3153                                         mute_point = mute_point + "Main";
3154                                 }
3155                         }
3156
3157                         _mute_master->set_mute_points (mute_point);
3158                         _mute_master->set_muted_by_self (true);
3159                 }
3160         }
3161
3162         if ((prop = node.property (X_("meter-point"))) != 0) {
3163                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
3164         }
3165
3166         /* do not carry over edit/mix groups from 2.X because (a) its hard (b) they
3167            don't mean the same thing.
3168         */
3169
3170         if ((prop = node.property (X_("order-keys"))) != 0) {
3171
3172                 int32_t n;
3173
3174                 string::size_type colon, equal;
3175                 string remaining = prop->value();
3176
3177                 while (remaining.length()) {
3178
3179                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
3180                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
3181                                         << endmsg;
3182                         } else {
3183                                 if (sscanf (remaining.substr (equal+1).c_str(), "%d", &n) != 1) {
3184                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
3185                                                 << endmsg;
3186                                 } else {
3187                                         string keyname = remaining.substr (0, equal);
3188
3189                                         if (keyname == "EditorSort" || keyname == "editor") {
3190                                                 info << string_compose(_("Converting deprecated order key for %1 using Editor order %2"), name (), n) << endmsg;
3191                                                 set_order_key (n);
3192                                         }
3193                                 }
3194                         }
3195
3196                         colon = remaining.find_first_of (':');
3197
3198                         if (colon != string::npos) {
3199                                 remaining = remaining.substr (colon+1);
3200                         } else {
3201                                 break;
3202                         }
3203                 }
3204         }
3205
3206         /* IOs */
3207
3208         nlist = node.children ();
3209         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
3210
3211                 child = *niter;
3212
3213                 if (child->name() == IO::state_node_name) {
3214
3215                         /* there is a note in IO::set_state_2X() about why we have to call
3216                            this directly.
3217                            */
3218
3219                         _input->set_state_2X (*child, version, true);
3220                         _output->set_state_2X (*child, version, false);
3221
3222                         if ((prop = child->property (X_("name"))) != 0) {
3223                                 Route::set_name (prop->value ());
3224                         }
3225
3226                         set_id (*child);
3227
3228                         if ((prop = child->property (X_("active"))) != 0) {
3229                                 bool yn = string_is_affirmative (prop->value());
3230                                 _active = !yn; // force switch
3231                                 set_active (yn, this);
3232                         }
3233
3234                         if ((prop = child->property (X_("gain"))) != 0) {
3235                                 gain_t val;
3236
3237                                 if (sscanf (prop->value().c_str(), "%f", &val) == 1) {
3238                                         _amp->gain_control()->set_value (val, Controllable::NoGroup);
3239                                 }
3240                         }
3241
3242                         /* Set up Panners in the IO */
3243                         XMLNodeList io_nlist = child->children ();
3244
3245                         XMLNodeConstIterator io_niter;
3246                         XMLNode *io_child;
3247
3248                         for (io_niter = io_nlist.begin(); io_niter != io_nlist.end(); ++io_niter) {
3249
3250                                 io_child = *io_niter;
3251
3252                                 if (io_child->name() == X_("Panner")) {
3253                                         _main_outs->panner_shell()->set_state(*io_child, version);
3254                                 } else if (io_child->name() == X_("Automation")) {
3255                                         /* IO's automation is for the fader */
3256                                         _amp->set_automation_xml_state (*io_child, Evoral::Parameter (GainAutomation));
3257                                 }
3258                         }
3259                 }
3260         }
3261
3262         XMLNodeList redirect_nodes;
3263
3264         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
3265
3266                 child = *niter;
3267
3268                 if (child->name() == X_("Send") || child->name() == X_("Insert")) {
3269                         redirect_nodes.push_back(child);
3270                 }
3271
3272         }
3273
3274         set_processor_state_2X (redirect_nodes, version);
3275
3276         Stateful::save_extra_xml (node);
3277
3278         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
3279                 child = *niter;
3280
3281                 if (child->name() == X_("Comment")) {
3282
3283                         /* XXX this is a terrible API design in libxml++ */
3284
3285                         XMLNode *cmt = *(child->children().begin());
3286                         _comment = cmt->content();
3287
3288                 } else if (child->name() == Controllable::xml_node_name && (prop = child->property("name")) != 0) {
3289                         if (prop->value() == X_("solo")) {
3290                                 _solo_control->set_state (*child, version);
3291                         } else if (prop->value() == X_("mute")) {
3292                                 _mute_control->set_state (*child, version);
3293                         }
3294
3295                 } else if (child->name() == X_("RemoteControl")) {
3296                         if ((prop = child->property (X_("id"))) != 0) {
3297                                 int32_t x;
3298                                 sscanf (prop->value().c_str(), "%d", &x);
3299                                 set_remote_control_id_internal (x);
3300                         }
3301
3302                 }
3303         }
3304
3305         return 0;
3306 }
3307
3308 XMLNode&
3309 Route::get_processor_state ()
3310 {
3311         XMLNode* root = new XMLNode (X_("redirects"));
3312         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3313                 root->add_child_nocopy ((*i)->state (true));
3314         }
3315
3316         return *root;
3317 }
3318
3319 void
3320 Route::set_processor_state_2X (XMLNodeList const & nList, int version)
3321 {
3322         /* We don't bother removing existing processors not in nList, as this
3323            method will only be called when creating a Route from scratch, not
3324            for undo purposes.  Just put processors in at the appropriate place
3325            in the list.
3326         */
3327
3328         for (XMLNodeConstIterator i = nList.begin(); i != nList.end(); ++i) {
3329                 add_processor_from_xml_2X (**i, version);
3330         }
3331 }
3332
3333 void
3334 Route::set_processor_state (const XMLNode& node)
3335 {
3336         const XMLNodeList &nlist = node.children();
3337         XMLNodeConstIterator niter;
3338         ProcessorList new_order;
3339         bool must_configure = false;
3340
3341         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
3342
3343                 XMLProperty const * prop = (*niter)->property ("type");
3344
3345                 if (prop->value() == "amp") {
3346                         _amp->set_state (**niter, Stateful::current_state_version);
3347                         new_order.push_back (_amp);
3348                 } else if (prop->value() == "trim") {
3349                         _trim->set_state (**niter, Stateful::current_state_version);
3350                         new_order.push_back (_trim);
3351                 } else if (prop->value() == "meter") {
3352                         _meter->set_state (**niter, Stateful::current_state_version);
3353                         new_order.push_back (_meter);
3354                 } else if (prop->value() == "delay") {
3355                         if (_delayline) {
3356                                 _delayline->set_state (**niter, Stateful::current_state_version);
3357                                 new_order.push_back (_delayline);
3358                         }
3359                 } else if (prop->value() == "main-outs") {
3360                         _main_outs->set_state (**niter, Stateful::current_state_version);
3361                 } else if (prop->value() == "intreturn") {
3362                         if (!_intreturn) {
3363                                 _intreturn.reset (new InternalReturn (_session));
3364                                 must_configure = true;
3365                         }
3366                         _intreturn->set_state (**niter, Stateful::current_state_version);
3367                 } else if (is_monitor() && prop->value() == "monitor") {
3368                         if (!_monitor_control) {
3369                                 _monitor_control.reset (new MonitorProcessor (_session));
3370                                 must_configure = true;
3371                         }
3372                         _monitor_control->set_state (**niter, Stateful::current_state_version);
3373                 } else if (prop->value() == "capture") {
3374                         /* CapturingProcessor should never be restored, it's always
3375                            added explicitly when needed */
3376                 } else {
3377                         ProcessorList::iterator o;
3378
3379                         for (o = _processors.begin(); o != _processors.end(); ++o) {
3380                                 XMLProperty const * id_prop = (*niter)->property(X_("id"));
3381                                 if (id_prop && (*o)->id() == id_prop->value()) {
3382                                         (*o)->set_state (**niter, Stateful::current_state_version);
3383                                         new_order.push_back (*o);
3384                                         break;
3385                                 }
3386                         }
3387
3388                         // If the processor (*niter) is not on the route then create it
3389
3390                         if (o == _processors.end()) {
3391
3392                                 boost::shared_ptr<Processor> processor;
3393
3394                                 if (prop->value() == "intsend") {
3395
3396                                         processor.reset (new InternalSend (_session, _pannable, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), boost::shared_ptr<Route>(), Delivery::Aux, true));
3397
3398                                 } else if (prop->value() == "ladspa" || prop->value() == "Ladspa" ||
3399                                            prop->value() == "lv2" ||
3400                                            prop->value() == "windows-vst" ||
3401                                            prop->value() == "lxvst" ||
3402                                            prop->value() == "luaproc" ||
3403                                            prop->value() == "audiounit") {
3404
3405                                         if (_session.get_disable_all_loaded_plugins ()) {
3406                                                 processor.reset (new UnknownProcessor (_session, **niter));
3407                                         } else {
3408                                                 processor.reset (new PluginInsert (_session));
3409                                                 processor->set_owner (this);
3410                                                 if (_strict_io) {
3411                                                         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(processor);
3412                                                         pi->set_strict_io (true);
3413                                                 }
3414
3415                                         }
3416                                 } else if (prop->value() == "port") {
3417
3418                                         processor.reset (new PortInsert (_session, _pannable, _mute_master));
3419
3420                                 } else if (prop->value() == "send") {
3421
3422                                         processor.reset (new Send (_session, _pannable, _mute_master, Delivery::Send, true));
3423                                         boost::shared_ptr<Send> send = boost::dynamic_pointer_cast<Send> (processor);
3424                                         send->SelfDestruct.connect_same_thread (*this,
3425                                                         boost::bind (&Route::processor_selfdestruct, this, boost::weak_ptr<Processor> (processor)));
3426
3427                                 } else {
3428                                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
3429                                         continue;
3430                                 }
3431
3432                                 if (processor->set_state (**niter, Stateful::current_state_version) != 0) {
3433                                         /* This processor could not be configured.  Turn it into a UnknownProcessor */
3434                                         processor.reset (new UnknownProcessor (_session, **niter));
3435                                 }
3436
3437                                 /* subscribe to Sidechain IO changes */
3438                                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (processor);
3439                                 if (pi && pi->has_sidechain ()) {
3440                                         pi->sidechain_input ()->changed.connect_same_thread (*this, boost::bind (&Route::sidechain_change_handler, this, _1, _2));
3441                                 }
3442
3443                                 /* we have to note the monitor send here, otherwise a new one will be created
3444                                    and the state of this one will be lost.
3445                                 */
3446                                 boost::shared_ptr<InternalSend> isend = boost::dynamic_pointer_cast<InternalSend> (processor);
3447                                 if (isend && isend->role() == Delivery::Listen) {
3448                                         _monitor_send = isend;
3449                                 }
3450
3451                                 /* it doesn't matter if invisible processors are added here, as they
3452                                    will be sorted out by setup_invisible_processors () shortly.
3453                                 */
3454
3455                                 new_order.push_back (processor);
3456                                 must_configure = true;
3457                         }
3458                 }
3459         }
3460
3461         {
3462                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
3463                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
3464                 _processors = new_order;
3465
3466                 if (must_configure) {
3467                         configure_processors_unlocked (0, &lm);
3468                 }
3469
3470                 for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3471
3472                         (*i)->set_owner (this);
3473                         (*i)->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false));
3474
3475                         boost::shared_ptr<PluginInsert> pi;
3476
3477                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
3478                                 if (pi->has_no_inputs ()) {
3479                                         _have_internal_generator = true;
3480                                         break;
3481                                 }
3482                         }
3483                 }
3484         }
3485
3486         reset_instrument_info ();
3487         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
3488         set_processor_positions ();
3489 }
3490
3491 void
3492 Route::curve_reallocate ()
3493 {
3494 //      _gain_automation_curve.finish_resize ();
3495 //      _pan_automation_curve.finish_resize ();
3496 }
3497
3498 void
3499 Route::silence (framecnt_t nframes)
3500 {
3501         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
3502         if (!lm.locked()) {
3503                 return;
3504         }
3505
3506         silence_unlocked (nframes);
3507 }
3508
3509 void
3510 Route::silence_unlocked (framecnt_t nframes)
3511 {
3512         /* Must be called with the processor lock held */
3513
3514         if (!_silent) {
3515
3516                 _output->silence (nframes);
3517
3518                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3519                         boost::shared_ptr<PluginInsert> pi;
3520
3521                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
3522                                 // skip plugins, they don't need anything when we're not active
3523                                 continue;
3524                         }
3525
3526                         (*i)->silence (nframes);
3527                 }
3528
3529                 if (nframes == _session.get_block_size()) {
3530                         // _silent = true;
3531                 }
3532         }
3533 }
3534
3535 void
3536 Route::add_internal_return ()
3537 {
3538         if (!_intreturn) {
3539                 _intreturn.reset (new InternalReturn (_session));
3540                 add_processor (_intreturn, PreFader);
3541         }
3542 }
3543
3544 void
3545 Route::add_send_to_internal_return (InternalSend* send)
3546 {
3547         Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3548
3549         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
3550                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
3551
3552                 if (d) {
3553                         return d->add_send (send);
3554                 }
3555         }
3556 }
3557
3558 void
3559 Route::remove_send_from_internal_return (InternalSend* send)
3560 {
3561         Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3562
3563         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
3564                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
3565
3566                 if (d) {
3567                         return d->remove_send (send);
3568                 }
3569         }
3570 }
3571
3572 void
3573 Route::enable_monitor_send ()
3574 {
3575         /* Caller must hold process lock */
3576         assert (!AudioEngine::instance()->process_lock().trylock());
3577
3578         /* master never sends to monitor section via the normal mechanism */
3579         assert (!is_master ());
3580         assert (!is_monitor ());
3581
3582         /* make sure we have one */
3583         if (!_monitor_send) {
3584                 _monitor_send.reset (new InternalSend (_session, _pannable, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), _session.monitor_out(), Delivery::Listen));
3585                 _monitor_send->set_display_to_user (false);
3586         }
3587
3588         /* set it up */
3589         configure_processors (0);
3590 }
3591
3592 /** Add an aux send to a route.
3593  *  @param route route to send to.
3594  *  @param before Processor to insert before, or 0 to insert at the end.
3595  */
3596 int
3597 Route::add_aux_send (boost::shared_ptr<Route> route, boost::shared_ptr<Processor> before)
3598 {
3599         assert (route != _session.monitor_out ());
3600
3601         {
3602                 Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3603
3604                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
3605
3606                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend> (*x);
3607
3608                         if (d && d->target_route() == route) {
3609                                 /* already listening via the specified IO: do nothing */
3610                                 return 0;
3611                         }
3612                 }
3613         }
3614
3615         try {
3616
3617                 boost::shared_ptr<InternalSend> listener;
3618
3619                 {
3620                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3621                         boost::shared_ptr<Pannable> sendpan (new Pannable (_session));
3622                         listener.reset (new InternalSend (_session, sendpan, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), route, Delivery::Aux));
3623                 }
3624
3625                 add_processor (listener, before);
3626
3627         } catch (failed_constructor& err) {
3628                 return -1;
3629         }
3630
3631         return 0;
3632 }
3633
3634 void
3635 Route::remove_aux_or_listen (boost::shared_ptr<Route> route)
3636 {
3637         ProcessorStreams err;
3638         ProcessorList::iterator tmp;
3639
3640         {
3641                 Glib::Threads::RWLock::ReaderLock rl(_processor_lock);
3642
3643                 /* have to do this early because otherwise processor reconfig
3644                  * will put _monitor_send back in the list
3645                  */
3646
3647                 if (route == _session.monitor_out()) {
3648                         _monitor_send.reset ();
3649                 }
3650
3651           again:
3652                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
3653
3654                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
3655
3656                         if (d && d->target_route() == route) {
3657                                 rl.release ();
3658                                 if (remove_processor (*x, &err, false) > 0) {
3659                                         rl.acquire ();
3660                                         continue;
3661                                 }
3662                                 rl.acquire ();
3663
3664                                 /* list could have been demolished while we dropped the lock
3665                                    so start over.
3666                                 */
3667                                 if (_session.engine().connected()) {
3668                                         /* i/o processors cannot be removed if the engine is not running
3669                                          * so don't live-loop in case the engine is N/A or dies
3670                                          */
3671                                         goto again;
3672                                 }
3673                         }
3674                 }
3675         }
3676 }
3677
3678 void
3679 Route::set_comment (string cmt, void *src)
3680 {
3681         _comment = cmt;
3682         comment_changed ();
3683         _session.set_dirty ();
3684 }
3685
3686 bool
3687 Route::add_fed_by (boost::shared_ptr<Route> other, bool via_sends_only)
3688 {
3689         FeedRecord fr (other, via_sends_only);
3690
3691         pair<FedBy::iterator,bool> result =  _fed_by.insert (fr);
3692
3693         if (!result.second) {
3694
3695                 /* already a record for "other" - make sure sends-only information is correct */
3696                 if (!via_sends_only && result.first->sends_only) {
3697                         FeedRecord* frp = const_cast<FeedRecord*>(&(*result.first));
3698                         frp->sends_only = false;
3699                 }
3700         }
3701
3702         return result.second;
3703 }
3704
3705 void
3706 Route::clear_fed_by ()
3707 {
3708         _fed_by.clear ();
3709 }
3710
3711 bool
3712 Route::feeds (boost::shared_ptr<Route> other, bool* via_sends_only)
3713 {
3714         const FedBy& fed_by (other->fed_by());
3715
3716         for (FedBy::const_iterator f = fed_by.begin(); f != fed_by.end(); ++f) {
3717                 boost::shared_ptr<Route> sr = f->r.lock();
3718
3719                 if (sr && (sr.get() == this)) {
3720
3721                         if (via_sends_only) {
3722                                 *via_sends_only = f->sends_only;
3723                         }
3724
3725                         return true;
3726                 }
3727         }
3728
3729         return false;
3730 }
3731
3732 IOVector
3733 Route::all_inputs () const
3734 {
3735         /* TODO, if this works as expected,
3736          * cache the IOVector and maintain it via
3737          * input_change_handler(), sidechain_change_handler() etc
3738          */
3739         IOVector ios;
3740         ios.push_back (_input);
3741
3742         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3743         for (ProcessorList::const_iterator r = _processors.begin(); r != _processors.end(); ++r) {
3744
3745                 boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*r);
3746                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*r);
3747                 if (pi != 0) {
3748                         assert (iop == 0);
3749                         iop = pi->sidechain();
3750                 }
3751
3752                 if (iop != 0 && iop->input()) {
3753                         ios.push_back (iop->input());
3754                 }
3755         }
3756         return ios;
3757 }
3758
3759 IOVector
3760 Route::all_outputs () const
3761 {
3762         IOVector ios;
3763         // _output is included via Delivery
3764         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3765         for (ProcessorList::const_iterator r = _processors.begin(); r != _processors.end(); ++r) {
3766                 boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*r);
3767                 if (iop != 0 && iop->output()) {
3768                         ios.push_back (iop->output());
3769                 }
3770         }
3771         return ios;
3772 }
3773
3774 bool
3775 Route::direct_feeds_according_to_reality (boost::shared_ptr<Route> other, bool* via_send_only)
3776 {
3777         DEBUG_TRACE (DEBUG::Graph, string_compose ("Feeds? %1\n", _name));
3778         if (other->all_inputs().fed_by (_output)) {
3779                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\tdirect FEEDS %2\n", other->name()));
3780                 if (via_send_only) {
3781                         *via_send_only = false;
3782                 }
3783
3784                 return true;
3785         }
3786
3787         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3788
3789         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); ++r) {
3790
3791                 boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*r);
3792                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*r);
3793                 if (pi != 0) {
3794                         assert (iop == 0);
3795                         iop = pi->sidechain();
3796                 }
3797
3798                 if (iop != 0) {
3799                         boost::shared_ptr<const IO> iop_out = iop->output();
3800                         if ((iop_out && other->all_inputs().fed_by (iop_out)) || iop->feeds (other)) {
3801                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does feed %2\n", iop->name(), other->name()));
3802                                 if (via_send_only) {
3803                                         *via_send_only = true;
3804                                 }
3805                                 return true;
3806                         } else {
3807                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does NOT feed %2\n", iop->name(), other->name()));
3808                         }
3809                 } else {
3810                         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tPROC %1 is not an IOP\n", (*r)->name()));
3811                 }
3812
3813         }
3814
3815         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tdoes NOT feed %1\n", other->name()));
3816         return false;
3817 }
3818
3819 bool
3820 Route::direct_feeds_according_to_graph (boost::shared_ptr<Route> other, bool* via_send_only)
3821 {
3822         return _session._current_route_graph.has (shared_from_this (), other, via_send_only);
3823 }
3824
3825 bool
3826 Route::feeds_according_to_graph (boost::shared_ptr<Route> other)
3827 {
3828         return _session._current_route_graph.feeds (shared_from_this (), other);
3829 }
3830
3831 /** Called from the (non-realtime) butler thread when the transport is stopped */
3832 void
3833 Route::nonrealtime_handle_transport_stopped (bool /*abort_ignored*/, bool /*did_locate*/, bool can_flush_processors)
3834 {
3835         framepos_t now = _session.transport_frame();
3836
3837         {
3838                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3839
3840                 Automatable::transport_stopped (now);
3841
3842                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3843
3844                         if (!_have_internal_generator && (Config->get_plugins_stop_with_transport() && can_flush_processors)) {
3845                                 (*i)->flush ();
3846                         }
3847
3848                         (*i)->transport_stopped (now);
3849                 }
3850         }
3851
3852         _roll_delay = _initial_delay;
3853 }
3854
3855 void
3856 Route::input_change_handler (IOChange change, void * /*src*/)
3857 {
3858         if ((change.type & IOChange::ConfigurationChanged)) {
3859                 /* This is called with the process lock held if change
3860                    contains ConfigurationChanged
3861                 */
3862                 configure_processors (0);
3863                 _phase_invert.resize (_input->n_ports().n_audio ());
3864                 io_changed (); /* EMIT SIGNAL */
3865         }
3866
3867         if (_soloed_by_others_upstream || _solo_isolated_by_upstream) {
3868                 int sbou = 0;
3869                 int ibou = 0;
3870                 boost::shared_ptr<RouteList> routes = _session.get_routes ();
3871                 if (_input->connected()) {
3872                         for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3873                                 if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3874                                         continue;
3875                                 }
3876                                 bool sends_only;
3877                                 bool does_feed = (*i)->direct_feeds_according_to_reality (shared_from_this(), &sends_only);
3878                                 if (does_feed && !sends_only) {
3879                                         if ((*i)->soloed()) {
3880                                                 ++sbou;
3881                                         }
3882                                         if ((*i)->solo_isolated()) {
3883                                                 ++ibou;
3884                                         }
3885                                 }
3886                         }
3887                 }
3888
3889                 int delta  = sbou - _soloed_by_others_upstream;
3890                 int idelta = ibou - _solo_isolated_by_upstream;
3891
3892                 if (idelta < -1) {
3893                         PBD::warning << string_compose (
3894                                         _("Invalid Solo-Isolate propagation: from:%1 new:%2 - old:%3 = delta:%4"),
3895                                         _name, ibou, _solo_isolated_by_upstream, idelta)
3896                                      << endmsg;
3897
3898                 }
3899
3900                 if (_soloed_by_others_upstream) {
3901                         // ignore new connections (they're not propagated)
3902                         if (delta <= 0) {
3903                                 mod_solo_by_others_upstream (delta);
3904                         }
3905                 }
3906
3907                 if (_solo_isolated_by_upstream) {
3908                         // solo-isolate currently only propagates downstream
3909                         if (idelta < 0) {
3910                                 mod_solo_isolated_by_upstream (false);
3911                         }
3912                         // TODO think: mod_solo_isolated_by_upstream() does not take delta arg,
3913                         // but idelta can't be smaller than -1, can it?
3914                         //_solo_isolated_by_upstream = ibou;
3915                 }
3916
3917                 // Session::route_solo_changed  does not propagate indirect solo-changes
3918                 // propagate downstream to tracks
3919                 for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3920                         if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3921                                 continue;
3922                         }
3923                         bool sends_only;
3924                         bool does_feed = feeds (*i, &sends_only);
3925                         if (delta <= 0 && does_feed && !sends_only) {
3926                                 (*i)->mod_solo_by_others_upstream (delta);
3927                         }
3928
3929                         if (idelta < 0 && does_feed && !sends_only) {
3930                                 (*i)->mod_solo_isolated_by_upstream (false);
3931                         }
3932                 }
3933         }
3934 }
3935
3936 void
3937 Route::output_change_handler (IOChange change, void * /*src*/)
3938 {
3939         if (_initial_io_setup) {
3940                 return;
3941         }
3942
3943         if ((change.type & IOChange::ConfigurationChanged)) {
3944                 /* This is called with the process lock held if change
3945                    contains ConfigurationChanged
3946                 */
3947                 configure_processors (0);
3948
3949                 if (is_master()) {
3950                         _session.reset_monitor_section();
3951                 }
3952
3953                 io_changed (); /* EMIT SIGNAL */
3954         }
3955
3956         if (_soloed_by_others_downstream) {
3957                 int sbod = 0;
3958                 /* checking all all downstream routes for
3959                  * explicit of implict solo is a rather drastic measure,
3960                  * ideally the input_change_handler() of the other route
3961                  * would propagate the change to us.
3962                  */
3963                 boost::shared_ptr<RouteList> routes = _session.get_routes ();
3964                 if (_output->connected()) {
3965                         for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3966                                 if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3967                                         continue;
3968                                 }
3969                                 bool sends_only;
3970                                 bool does_feed = direct_feeds_according_to_reality (*i, &sends_only);
3971                                 if (does_feed && !sends_only) {
3972                                         if ((*i)->soloed()) {
3973                                                 ++sbod;
3974                                                 break;
3975                                         }
3976                                 }
3977                         }
3978                 }
3979                 int delta = sbod - _soloed_by_others_downstream;
3980                 if (delta <= 0) {
3981                         // do not allow new connections to change implicit solo (no propagation)
3982                         mod_solo_by_others_downstream (delta);
3983                         // Session::route_solo_changed() does not propagate indirect solo-changes
3984                         // propagate upstream to tracks
3985                         for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3986                                 if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3987                                         continue;
3988                                 }
3989                                 bool sends_only;
3990                                 bool does_feed = (*i)->feeds (shared_from_this(), &sends_only);
3991                                 if (delta != 0 && does_feed && !sends_only) {
3992                                         (*i)->mod_solo_by_others_downstream (delta);
3993                                 }
3994                         }
3995
3996                 }
3997         }
3998 }
3999
4000 void
4001 Route::sidechain_change_handler (IOChange change, void* src)
4002 {
4003         if (_initial_io_setup || _in_sidechain_setup) {
4004                 return;
4005         }
4006
4007         input_change_handler (change, src);
4008 }
4009
4010 uint32_t
4011 Route::pans_required () const
4012 {
4013         if (n_outputs().n_audio() < 2) {
4014                 return 0;
4015         }
4016
4017         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
4018 }
4019
4020 int
4021 Route::no_roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, bool session_state_changing)
4022 {
4023         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
4024
4025         if (!lm.locked()) {
4026                 return 0;
4027         }
4028
4029         if (n_outputs().n_total() == 0) {
4030                 return 0;
4031         }
4032
4033         if (!_active || n_inputs() == ChanCount::ZERO)  {
4034                 silence_unlocked (nframes);
4035                 return 0;
4036         }
4037
4038         if (session_state_changing) {
4039                 if (_session.transport_speed() != 0.0f) {
4040                         /* we're rolling but some state is changing (e.g. our diskstream contents)
4041                            so we cannot use them. Be silent till this is over.
4042
4043                            XXX note the absurdity of ::no_roll() being called when we ARE rolling!
4044                         */
4045                         silence_unlocked (nframes);
4046                         return 0;
4047                 }
4048                 /* we're really not rolling, so we're either delivery silence or actually
4049                    monitoring, both of which are safe to do while session_state_changing is true.
4050                 */
4051         }
4052
4053         BufferSet& bufs = _session.get_route_buffers (n_process_buffers());
4054
4055         fill_buffers_with_input (bufs, _input, nframes);
4056
4057         if (_meter_point == MeterInput) {
4058                 _meter->run (bufs, start_frame, end_frame, nframes, true);
4059         }
4060
4061         _amp->apply_gain_automation (false);
4062         _trim->apply_gain_automation (false);
4063         passthru (bufs, start_frame, end_frame, nframes, 0);
4064
4065         return 0;
4066 }
4067
4068 int
4069 Route::roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& /* need_butler */)
4070 {
4071         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
4072         if (!lm.locked()) {
4073                 return 0;
4074         }
4075
4076         if (n_outputs().n_total() == 0) {
4077                 return 0;
4078         }
4079
4080         if (!_active || n_inputs().n_total() == 0) {
4081                 silence_unlocked (nframes);
4082                 return 0;
4083         }
4084
4085         framepos_t unused = 0;
4086
4087         if ((nframes = check_initial_delay (nframes, unused)) == 0) {
4088                 return 0;
4089         }
4090
4091         _silent = false;
4092
4093         BufferSet& bufs = _session.get_route_buffers (n_process_buffers());
4094
4095         fill_buffers_with_input (bufs, _input, nframes);
4096
4097         if (_meter_point == MeterInput) {
4098                 _meter->run (bufs, start_frame, end_frame, nframes, true);
4099         }
4100
4101         passthru (bufs, start_frame, end_frame, nframes, declick);
4102
4103         return 0;
4104 }
4105
4106 int
4107 Route::silent_roll (pframes_t nframes, framepos_t /*start_frame*/, framepos_t /*end_frame*/, bool& /* need_butler */)
4108 {
4109         silence (nframes);
4110         return 0;
4111 }
4112
4113 void
4114 Route::flush_processors ()
4115 {
4116         /* XXX shouldn't really try to take this lock, since
4117            this is called from the RT audio thread.
4118         */
4119
4120         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4121
4122         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4123                 (*i)->flush ();
4124         }
4125 }
4126
4127 #ifdef __clang__
4128 __attribute__((annotate("realtime")))
4129 #endif
4130 bool
4131 Route::apply_processor_changes_rt ()
4132 {
4133         int emissions = EmitNone;
4134
4135         if (_pending_meter_point != _meter_point) {
4136                 Glib::Threads::RWLock::WriterLock pwl (_processor_lock, Glib::Threads::TRY_LOCK);
4137                 if (pwl.locked()) {
4138                         /* meters always have buffers for 'processor_max_streams'
4139                          * they can be re-positioned without re-allocation */
4140                         if (set_meter_point_unlocked()) {
4141                                 emissions |= EmitMeterChanged | EmitMeterVisibilityChange;;
4142                         } else {
4143                                 emissions |= EmitMeterChanged;
4144                         }
4145                 }
4146         }
4147
4148         bool changed = false;
4149
4150         if (g_atomic_int_get (&_pending_process_reorder)) {
4151                 Glib::Threads::RWLock::WriterLock pwl (_processor_lock, Glib::Threads::TRY_LOCK);
4152                 if (pwl.locked()) {
4153                         apply_processor_order (_pending_processor_order);
4154                         setup_invisible_processors ();
4155                         changed = true;
4156                         g_atomic_int_set (&_pending_process_reorder, 0);
4157                         emissions |= EmitRtProcessorChange;
4158                 }
4159         }
4160         if (changed) {
4161                 set_processor_positions ();
4162         }
4163         if (emissions != 0) {
4164                 g_atomic_int_set (&_pending_signals, emissions);
4165                 return true;
4166         }
4167         return (!selfdestruct_sequence.empty ());
4168 }
4169
4170 void
4171 Route::emit_pending_signals ()
4172 {
4173         int sig = g_atomic_int_and (&_pending_signals, 0);
4174         if (sig & EmitMeterChanged) {
4175                 _meter->emit_configuration_changed();
4176                 meter_change (); /* EMIT SIGNAL */
4177                 if (sig & EmitMeterVisibilityChange) {
4178                 processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, true)); /* EMIT SIGNAL */
4179                 } else {
4180                 processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, false)); /* EMIT SIGNAL */
4181                 }
4182         }
4183         if (sig & EmitRtProcessorChange) {
4184                 processors_changed (RouteProcessorChange (RouteProcessorChange::RealTimeChange)); /* EMIT SIGNAL */
4185         }
4186
4187         /* this would be a job for the butler.
4188          * Conceptually we should not take processe/processor locks here.
4189          * OTOH its more efficient (less overhead for summoning the butler and
4190          * telling her what do do) and signal emission is called
4191          * directly after the process callback, which decreases the chance
4192          * of x-runs when taking the locks.
4193          */
4194         while (!selfdestruct_sequence.empty ()) {
4195                 Glib::Threads::Mutex::Lock lx (selfdestruct_lock);
4196                 if (selfdestruct_sequence.empty ()) { break; } // re-check with lock
4197                 boost::shared_ptr<Processor> proc = selfdestruct_sequence.back ().lock ();
4198                 selfdestruct_sequence.pop_back ();
4199                 lx.release ();
4200                 if (proc) {
4201                         remove_processor (proc);
4202                 }
4203         }
4204 }
4205
4206 void
4207 Route::set_meter_point (MeterPoint p, bool force)
4208 {
4209         if (_pending_meter_point == p && !force) {
4210                 return;
4211         }
4212
4213         if (force || !AudioEngine::instance()->running()) {
4214                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
4215                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
4216                 _pending_meter_point = p;
4217                 _meter->emit_configuration_changed();
4218                 meter_change (); /* EMIT SIGNAL */
4219                 if (set_meter_point_unlocked()) {
4220                         processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, true)); /* EMIT SIGNAL */
4221                 } else {
4222                         processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, false)); /* EMIT SIGNAL */
4223                 }
4224         } else {
4225                 _pending_meter_point = p;
4226         }
4227 }
4228
4229
4230 #ifdef __clang__
4231 __attribute__((annotate("realtime")))
4232 #endif
4233 bool
4234 Route::set_meter_point_unlocked ()
4235 {
4236 #ifndef NDEBUG
4237         /* Caller must hold process and processor write lock */
4238         assert (!AudioEngine::instance()->process_lock().trylock());
4239         Glib::Threads::RWLock::WriterLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
4240         assert (!lm.locked ());
4241 #endif
4242
4243         _meter_point = _pending_meter_point;
4244
4245         bool meter_was_visible_to_user = _meter->display_to_user ();
4246
4247         if (!_custom_meter_position_noted) {
4248                 maybe_note_meter_position ();
4249         }
4250
4251         if (_meter_point != MeterCustom) {
4252
4253                 _meter->set_display_to_user (false);
4254
4255                 setup_invisible_processors ();
4256
4257         } else {
4258                 _meter->set_display_to_user (true);
4259
4260                 /* If we have a previous position for the custom meter, try to put it there */
4261                 boost::shared_ptr<Processor> after = _processor_after_last_custom_meter.lock ();
4262                 if (after) {
4263                         ProcessorList::iterator i = find (_processors.begin(), _processors.end(), after);
4264                         if (i != _processors.end ()) {
4265                                 _processors.remove (_meter);
4266                                 _processors.insert (i, _meter);
4267                         }
4268                 } else {// at end, right before the mains_out/panner
4269                         _processors.remove (_meter);
4270                         ProcessorList::iterator main = _processors.end();
4271                         _processors.insert (--main, _meter);
4272                 }
4273         }
4274
4275         /* Set up the meter for its new position */
4276
4277         ProcessorList::iterator loc = find (_processors.begin(), _processors.end(), _meter);
4278
4279         ChanCount m_in;
4280
4281         if (loc == _processors.begin()) {
4282                 m_in = _input->n_ports();
4283         } else {
4284                 ProcessorList::iterator before = loc;
4285                 --before;
4286                 m_in = (*before)->output_streams ();
4287         }
4288
4289         _meter->reflect_inputs (m_in);
4290
4291         /* we do not need to reconfigure the processors, because the meter
4292            (a) is always ready to handle processor_max_streams
4293            (b) is always an N-in/N-out processor, and thus moving
4294            it doesn't require any changes to the other processors.
4295         */
4296
4297         /* these should really be done after releasing the lock
4298          * but all those signals are subscribed to with gui_thread()
4299          * so we're safe.
4300          */
4301          return (_meter->display_to_user() != meter_was_visible_to_user);
4302 }
4303
4304 void
4305 Route::listen_position_changed ()
4306 {
4307         {
4308                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
4309                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
4310                 ProcessorState pstate (this);
4311
4312                 if (configure_processors_unlocked (0, &lm)) {
4313                         DEBUG_TRACE (DEBUG::Processors, "---- CONFIGURATION FAILED.\n");
4314                         pstate.restore ();
4315                         configure_processors_unlocked (0, &lm); // it worked before we tried to add it ...
4316                         return;
4317                 }
4318         }
4319
4320         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
4321         _session.set_dirty ();
4322 }
4323
4324 boost::shared_ptr<CapturingProcessor>
4325 Route::add_export_point()
4326 {
4327         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4328         if (!_capturing_processor) {
4329                 lm.release();
4330                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
4331                 Glib::Threads::RWLock::WriterLock lw (_processor_lock);
4332
4333                 _capturing_processor.reset (new CapturingProcessor (_session));
4334                 _capturing_processor->activate ();
4335
4336                 configure_processors_unlocked (0, &lw);
4337
4338         }
4339
4340         return _capturing_processor;
4341 }
4342
4343 framecnt_t
4344 Route::update_signal_latency ()
4345 {
4346         framecnt_t l = _output->user_latency();
4347         framecnt_t lamp = 0;
4348         bool before_amp = true;
4349         framecnt_t ltrim = 0;
4350         bool before_trim = true;
4351
4352         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4353                 if ((*i)->active ()) {
4354                         l += (*i)->signal_latency ();
4355                 }
4356                 if ((*i) == _amp) {
4357                         before_amp = false;
4358                 }
4359                 if ((*i) == _trim) {
4360                         before_amp = false;
4361                 }
4362                 if (before_amp) {
4363                         lamp = l;
4364                 }
4365                 if (before_trim) {
4366                         lamp = l;
4367                 }
4368         }
4369
4370         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: internal signal latency = %2\n", _name, l));
4371
4372         // TODO: (lamp - _signal_latency) to sync to output (read-ahed),  currently _roll_delay shifts this around
4373         _signal_latency_at_amp_position = lamp;
4374         _signal_latency_at_trim_position = ltrim;
4375
4376         if (_signal_latency != l) {
4377                 _signal_latency = l;
4378                 signal_latency_changed (); /* EMIT SIGNAL */
4379         }
4380
4381         return _signal_latency;
4382 }
4383
4384 void
4385 Route::set_user_latency (framecnt_t nframes)
4386 {
4387         _output->set_user_latency (nframes);
4388         _session.update_latency_compensation ();
4389 }
4390
4391 void
4392 Route::set_latency_compensation (framecnt_t longest_session_latency)
4393 {
4394         framecnt_t old = _initial_delay;
4395
4396         if (_signal_latency < longest_session_latency) {
4397                 _initial_delay = longest_session_latency - _signal_latency;
4398         } else {
4399                 _initial_delay = 0;
4400         }
4401
4402         DEBUG_TRACE (DEBUG::Latency, string_compose (
4403                              "%1: compensate for maximum latency of %2,"
4404                              "given own latency of %3, using initial delay of %4\n",
4405                              name(), longest_session_latency, _signal_latency, _initial_delay));
4406
4407         if (_initial_delay != old) {
4408                 initial_delay_changed (); /* EMIT SIGNAL */
4409         }
4410
4411         if (_session.transport_stopped()) {
4412                 _roll_delay = _initial_delay;
4413         }
4414 }
4415
4416 void
4417 Route::set_block_size (pframes_t nframes)
4418 {
4419         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4420                 (*i)->set_block_size (nframes);
4421         }
4422
4423         _session.ensure_buffers (n_process_buffers ());
4424 }
4425
4426 void
4427 Route::protect_automation ()
4428 {
4429         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
4430                 (*i)->protect_automation();
4431 }
4432
4433 /** @param declick 1 to set a pending declick fade-in,
4434  *                -1 to set a pending declick fade-out
4435  */
4436 void
4437 Route::set_pending_declick (int declick)
4438 {
4439         if (_declickable) {
4440                 /* this call is not allowed to turn off a pending declick */
4441                 if (declick) {
4442                         _pending_declick = declick;
4443                 }
4444         } else {
4445                 _pending_declick = 0;
4446         }
4447 }
4448
4449 /** Shift automation forwards from a particular place, thereby inserting time.
4450  *  Adds undo commands for any shifts that are performed.
4451  *
4452  * @param pos Position to start shifting from.
4453  * @param frames Amount to shift forwards by.
4454  */
4455
4456 void
4457 Route::shift (framepos_t pos, framecnt_t frames)
4458 {
4459         /* gain automation */
4460         {
4461                 boost::shared_ptr<AutomationControl> gc = _amp->gain_control();
4462
4463                 XMLNode &before = gc->alist()->get_state ();
4464                 gc->alist()->shift (pos, frames);
4465                 XMLNode &after = gc->alist()->get_state ();
4466                 _session.add_command (new MementoCommand<AutomationList> (*gc->alist().get(), &before, &after));
4467         }
4468
4469         /* gain automation */
4470         {
4471                 boost::shared_ptr<AutomationControl> gc = _trim->gain_control();
4472
4473                 XMLNode &before = gc->alist()->get_state ();
4474                 gc->alist()->shift (pos, frames);
4475                 XMLNode &after = gc->alist()->get_state ();
4476                 _session.add_command (new MementoCommand<AutomationList> (*gc->alist().get(), &before, &after));
4477         }
4478
4479         // TODO mute automation ??
4480
4481         /* pan automation */
4482         if (_pannable) {
4483                 ControlSet::Controls& c (_pannable->controls());
4484
4485                 for (ControlSet::Controls::const_iterator ci = c.begin(); ci != c.end(); ++ci) {
4486                         boost::shared_ptr<AutomationControl> pc = boost::dynamic_pointer_cast<AutomationControl> (ci->second);
4487                         if (pc) {
4488                                 boost::shared_ptr<AutomationList> al = pc->alist();
4489                                 XMLNode& before = al->get_state ();
4490                                 al->shift (pos, frames);
4491                                 XMLNode& after = al->get_state ();
4492                                 _session.add_command (new MementoCommand<AutomationList> (*al.get(), &before, &after));
4493                         }
4494                 }
4495         }
4496
4497         /* redirect automation */
4498         {
4499                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4500                 for (ProcessorList::iterator i = _processors.begin (); i != _processors.end (); ++i) {
4501
4502                         set<Evoral::Parameter> parameters = (*i)->what_can_be_automated();
4503
4504                         for (set<Evoral::Parameter>::const_iterator p = parameters.begin (); p != parameters.end (); ++p) {
4505                                 boost::shared_ptr<AutomationControl> ac = (*i)->automation_control (*p);
4506                                 if (ac) {
4507                                         boost::shared_ptr<AutomationList> al = ac->alist();
4508                                         XMLNode &before = al->get_state ();
4509                                         al->shift (pos, frames);
4510                                         XMLNode &after = al->get_state ();
4511                                         _session.add_command (new MementoCommand<AutomationList> (*al.get(), &before, &after));
4512                                 }
4513                         }
4514                 }
4515         }
4516 }
4517
4518 void
4519 Route::set_plugin_state_dir (boost::weak_ptr<Processor> p, const std::string& d)
4520 {
4521         boost::shared_ptr<Processor> processor (p.lock ());
4522         boost::shared_ptr<PluginInsert> pi  = boost::dynamic_pointer_cast<PluginInsert> (processor);
4523         if (!pi) {
4524                 return;
4525         }
4526         pi->set_state_dir (d);
4527 }
4528
4529 int
4530 Route::save_as_template (const string& path, const string& name)
4531 {
4532         std::string state_dir = path.substr (0, path.find_last_of ('.')); // strip template_suffix
4533         PBD::Unwinder<std::string> uw (_session._template_state_dir, state_dir);
4534
4535         XMLNode& node (state (false));
4536
4537         XMLTree tree;
4538
4539         IO::set_name_in_state (*node.children().front(), name);
4540
4541         tree.set_root (&node);
4542
4543         /* return zero on success, non-zero otherwise */
4544         return !tree.write (path.c_str());
4545 }
4546
4547
4548 bool
4549 Route::set_name (const string& str)
4550 {
4551         if (str == name()) {
4552                 return true;
4553         }
4554
4555         string name = Route::ensure_track_or_route_name (str, _session);
4556         SessionObject::set_name (name);
4557
4558         bool ret = (_input->set_name(name) && _output->set_name(name));
4559
4560         if (ret) {
4561                 /* rename the main outs. Leave other IO processors
4562                  * with whatever name they already have, because its
4563                  * just fine as it is (it will not contain the route
4564                  * name if its a port insert, port send or port return).
4565                  */
4566
4567                 if (_main_outs) {
4568                         if (_main_outs->set_name (name)) {
4569                                 /* XXX returning false here is stupid because
4570                                    we already changed the route name.
4571                                 */
4572                                 return false;
4573                         }
4574                 }
4575         }
4576
4577         return ret;
4578 }
4579
4580 /** Set the name of a route in an XML description.
4581  *  @param node XML <Route> node to set the name in.
4582  *  @param name New name.
4583  */
4584 void
4585 Route::set_name_in_state (XMLNode& node, string const & name, bool rename_playlist)
4586 {
4587         node.add_property (X_("name"), name);
4588
4589         XMLNodeList children = node.children();
4590         for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
4591
4592                 if ((*i)->name() == X_("IO")) {
4593
4594                         IO::set_name_in_state (**i, name);
4595
4596                 } else if ((*i)->name() == X_("Processor")) {
4597
4598                         XMLProperty const * role = (*i)->property (X_("role"));
4599                         if (role && role->value() == X_("Main")) {
4600                                 (*i)->add_property (X_("name"), name);
4601                         }
4602
4603                 } else if ((*i)->name() == X_("Diskstream")) {
4604
4605                         if (rename_playlist) {
4606                                 (*i)->add_property (X_("playlist"), string_compose ("%1.1", name).c_str());
4607                         }
4608                         (*i)->add_property (X_("name"), name);
4609
4610                 }
4611         }
4612 }
4613
4614 boost::shared_ptr<Send>
4615 Route::internal_send_for (boost::shared_ptr<const Route> target) const
4616 {
4617         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4618
4619         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4620                 boost::shared_ptr<InternalSend> send;
4621
4622                 if ((send = boost::dynamic_pointer_cast<InternalSend>(*i)) != 0) {
4623                         if (send->target_route() == target) {
4624                                 return send;
4625                         }
4626                 }
4627         }
4628
4629         return boost::shared_ptr<Send>();
4630 }
4631
4632 /** @param c Audio channel index.
4633  *  @param yn true to invert phase, otherwise false.
4634  */
4635 void
4636 Route::set_phase_invert (uint32_t c, bool yn)
4637 {
4638         if (_phase_invert[c] != yn) {
4639                 _phase_invert[c] = yn;
4640                 phase_invert_changed (); /* EMIT SIGNAL */
4641                 _phase_control->Changed(); /* EMIT SIGNAL */
4642                 _session.set_dirty ();
4643         }
4644 }
4645
4646 void
4647 Route::set_phase_invert (boost::dynamic_bitset<> p)
4648 {
4649         if (_phase_invert != p) {
4650                 _phase_invert = p;
4651                 phase_invert_changed (); /* EMIT SIGNAL */
4652                 _session.set_dirty ();
4653         }
4654 }
4655
4656 bool
4657 Route::phase_invert (uint32_t c) const
4658 {
4659         return _phase_invert[c];
4660 }
4661
4662 boost::dynamic_bitset<>
4663 Route::phase_invert () const
4664 {
4665         return _phase_invert;
4666 }
4667
4668 void
4669 Route::set_denormal_protection (bool yn)
4670 {
4671         if (_denormal_protection != yn) {
4672                 _denormal_protection = yn;
4673                 denormal_protection_changed (); /* EMIT SIGNAL */
4674         }
4675 }
4676
4677 bool
4678 Route::denormal_protection () const
4679 {
4680         return _denormal_protection;
4681 }
4682
4683 void
4684 Route::set_active (bool yn, void* src)
4685 {
4686         if (_session.transport_rolling()) {
4687                 return;
4688         }
4689
4690         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_route_active()) {
4691                 _route_group->foreach_route (boost::bind (&Route::set_active, _1, yn, _route_group));
4692                 return;
4693         }
4694
4695         if (_active != yn) {
4696                 _active = yn;
4697                 _input->set_active (yn);
4698                 _output->set_active (yn);
4699                 active_changed (); // EMIT SIGNAL
4700                 _session.set_dirty ();
4701         }
4702 }
4703
4704 boost::shared_ptr<Pannable>
4705 Route::pannable() const
4706 {
4707         return _pannable;
4708 }
4709
4710 boost::shared_ptr<Panner>
4711 Route::panner() const
4712 {
4713         /* may be null ! */
4714         return _main_outs->panner_shell()->panner();
4715 }
4716
4717 boost::shared_ptr<PannerShell>
4718 Route::panner_shell() const
4719 {
4720         return _main_outs->panner_shell();
4721 }
4722
4723 boost::shared_ptr<GainControl>
4724 Route::gain_control() const
4725 {
4726         return _gain_control;
4727 }
4728
4729 boost::shared_ptr<GainControl>
4730 Route::trim_control() const
4731 {
4732         return _trim_control;
4733 }
4734
4735 boost::shared_ptr<Route::PhaseControllable>
4736 Route::phase_control() const
4737 {
4738         if (phase_invert().size()) {
4739                 return _phase_control;
4740         } else {
4741                 return boost::shared_ptr<PhaseControllable>();
4742         }
4743 }
4744
4745 boost::shared_ptr<AutomationControl>
4746 Route::get_control (const Evoral::Parameter& param)
4747 {
4748         /* either we own the control or .... */
4749
4750         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(control (param));
4751
4752         if (!c) {
4753
4754                 /* maybe one of our processors does or ... */
4755
4756                 Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
4757                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4758                         if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->control (param))) != 0) {
4759                                 break;
4760                         }
4761                 }
4762         }
4763
4764         if (!c) {
4765
4766                 /* nobody does so we'll make a new one */
4767
4768                 c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
4769                 add_control(c);
4770         }
4771
4772         return c;
4773 }
4774
4775 boost::shared_ptr<Processor>
4776 Route::nth_plugin (uint32_t n) const
4777 {
4778         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4779         ProcessorList::const_iterator i;
4780
4781         for (i = _processors.begin(); i != _processors.end(); ++i) {
4782                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
4783                         if (n-- == 0) {
4784                                 return *i;
4785                         }
4786                 }
4787         }
4788
4789         return boost::shared_ptr<Processor> ();
4790 }
4791
4792 boost::shared_ptr<Processor>
4793 Route::nth_send (uint32_t n) const
4794 {
4795         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4796         ProcessorList::const_iterator i;
4797
4798         for (i = _processors.begin(); i != _processors.end(); ++i) {
4799                 if (boost::dynamic_pointer_cast<Send> (*i)) {
4800
4801                         if ((*i)->name().find (_("Monitor")) == 0) {
4802                                 /* send to monitor section is not considered
4803                                    to be an accessible send.
4804                                 */
4805                                 continue;
4806                         }
4807
4808                         if (n-- == 0) {
4809                                 return *i;
4810                         }
4811                 }
4812         }
4813
4814         return boost::shared_ptr<Processor> ();
4815 }
4816
4817 bool
4818 Route::has_io_processor_named (const string& name)
4819 {
4820         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4821         ProcessorList::iterator i;
4822
4823         for (i = _processors.begin(); i != _processors.end(); ++i) {
4824                 if (boost::dynamic_pointer_cast<Send> (*i) ||
4825                     boost::dynamic_pointer_cast<PortInsert> (*i)) {
4826                         if ((*i)->name() == name) {
4827                                 return true;
4828                         }
4829                 }
4830         }
4831
4832         return false;
4833 }
4834
4835 MuteMaster::MutePoint
4836 Route::mute_points () const
4837 {
4838         return _mute_master->mute_points ();
4839 }
4840
4841 void
4842 Route::set_processor_positions ()
4843 {
4844         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4845
4846         bool had_amp = false;
4847         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4848                 (*i)->set_pre_fader (!had_amp);
4849                 if (*i == _amp) {
4850                         had_amp = true;
4851                 }
4852         }
4853 }
4854
4855 /** Called when there is a proposed change to the input port count */
4856 bool
4857 Route::input_port_count_changing (ChanCount to)
4858 {
4859         list<pair<ChanCount, ChanCount> > c = try_configure_processors (to, 0);
4860         if (c.empty()) {
4861                 /* The processors cannot be configured with the new input arrangement, so
4862                    block the change.
4863                 */
4864                 return true;
4865         }
4866
4867         /* The change is ok */
4868         return false;
4869 }
4870
4871 /** Called when there is a proposed change to the output port count */
4872 bool
4873 Route::output_port_count_changing (ChanCount to)
4874 {
4875         if (_strict_io && !_in_configure_processors) {
4876                 return true;
4877         }
4878         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4879                 if (processor_out_streams.get(*t) > to.get(*t)) {
4880                         return true;
4881                 }
4882         }
4883         /* The change is ok */
4884         return false;
4885 }
4886
4887 list<string>
4888 Route::unknown_processors () const
4889 {
4890         list<string> p;
4891
4892         if (_session.get_disable_all_loaded_plugins ()) {
4893                 // Do not list "missing plugins" if they are explicitly disabled
4894                 return p;
4895         }
4896
4897         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4898         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4899                 if (boost::dynamic_pointer_cast<UnknownProcessor const> (*i)) {
4900                         p.push_back ((*i)->name ());
4901                 }
4902         }
4903
4904         return p;
4905 }
4906
4907
4908 framecnt_t
4909 Route::update_port_latencies (PortSet& from, PortSet& to, bool playback, framecnt_t our_latency) const
4910 {
4911         /* we assume that all our input ports feed all our output ports. its not
4912            universally true, but the alternative is way too corner-case to worry about.
4913         */
4914
4915         LatencyRange all_connections;
4916
4917         if (from.empty()) {
4918                 all_connections.min = 0;
4919                 all_connections.max = 0;
4920         } else {
4921                 all_connections.min = ~((pframes_t) 0);
4922                 all_connections.max = 0;
4923
4924                 /* iterate over all "from" ports and determine the latency range for all of their
4925                    connections to the "outside" (outside of this Route).
4926                 */
4927
4928                 for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
4929
4930                         LatencyRange range;
4931
4932                         p->get_connected_latency_range (range, playback);
4933
4934                         all_connections.min = min (all_connections.min, range.min);
4935                         all_connections.max = max (all_connections.max, range.max);
4936                 }
4937         }
4938
4939         /* set the "from" port latencies to the max/min range of all their connections */
4940
4941         for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
4942                 p->set_private_latency_range (all_connections, playback);
4943         }
4944
4945         /* set the ports "in the direction of the flow" to the same value as above plus our own signal latency */
4946
4947         all_connections.min += our_latency;
4948         all_connections.max += our_latency;
4949
4950         for (PortSet::iterator p = to.begin(); p != to.end(); ++p) {
4951                 p->set_private_latency_range (all_connections, playback);
4952         }
4953
4954         return all_connections.max;
4955 }
4956
4957 framecnt_t
4958 Route::set_private_port_latencies (bool playback) const
4959 {
4960         framecnt_t own_latency = 0;
4961
4962         /* Processor list not protected by lock: MUST BE CALLED FROM PROCESS THREAD
4963            OR LATENCY CALLBACK.
4964
4965            This is called (early) from the latency callback. It computes the REAL
4966            latency associated with each port and stores the result as the "private"
4967            latency of the port. A later call to Route::set_public_port_latencies()
4968            sets all ports to the same value to reflect the fact that we do latency
4969            compensation and so all signals are delayed by the same amount as they
4970            flow through ardour.
4971         */
4972
4973         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4974                 if ((*i)->active ()) {
4975                         own_latency += (*i)->signal_latency ();
4976                 }
4977         }
4978
4979         if (playback) {
4980                 /* playback: propagate latency from "outside the route" to outputs to inputs */
4981                 return update_port_latencies (_output->ports (), _input->ports (), true, own_latency);
4982         } else {
4983                 /* capture: propagate latency from "outside the route" to inputs to outputs */
4984                 return update_port_latencies (_input->ports (), _output->ports (), false, own_latency);
4985         }
4986 }
4987
4988 void
4989 Route::set_public_port_latencies (framecnt_t value, bool playback) const
4990 {
4991         /* this is called to set the JACK-visible port latencies, which take
4992            latency compensation into account.
4993         */
4994
4995         LatencyRange range;
4996
4997         range.min = value;
4998         range.max = value;
4999
5000         {
5001                 const PortSet& ports (_input->ports());
5002                 for (PortSet::const_iterator p = ports.begin(); p != ports.end(); ++p) {
5003                         p->set_public_latency_range (range, playback);
5004                 }
5005         }
5006
5007         {
5008                 const PortSet& ports (_output->ports());
5009                 for (PortSet::const_iterator p = ports.begin(); p != ports.end(); ++p) {
5010                         p->set_public_latency_range (range, playback);
5011                 }
5012         }
5013 }
5014
5015 /** Put the invisible processors in the right place in _processors.
5016  *  Must be called with a writer lock on _processor_lock held.
5017  */
5018 #ifdef __clang__
5019 __attribute__((annotate("realtime")))
5020 #endif
5021 void
5022 Route::setup_invisible_processors ()
5023 {
5024 #ifndef NDEBUG
5025         Glib::Threads::RWLock::WriterLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
5026         assert (!lm.locked ());
5027 #endif
5028
5029         if (!_main_outs) {
5030                 /* too early to be doing this stuff */
5031                 return;
5032         }
5033
5034         /* we'll build this new list here and then use it
5035          *
5036          * TODO put the ProcessorList is on the stack for RT-safety.
5037          */
5038
5039         ProcessorList new_processors;
5040
5041         /* find visible processors */
5042
5043         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5044                 if ((*i)->display_to_user ()) {
5045                         new_processors.push_back (*i);
5046                 }
5047         }
5048
5049         /* find the amp */
5050
5051         ProcessorList::iterator amp = new_processors.begin ();
5052         while (amp != new_processors.end() && *amp != _amp) {
5053                 ++amp;
5054         }
5055
5056         assert (amp != new_processors.end ());
5057
5058         /* and the processor after the amp */
5059
5060         ProcessorList::iterator after_amp = amp;
5061         ++after_amp;
5062
5063         /* METER */
5064
5065         if (_meter) {
5066                 switch (_meter_point) {
5067                 case MeterInput:
5068                         assert (!_meter->display_to_user ());
5069                         new_processors.push_front (_meter);
5070                         break;
5071                 case MeterPreFader:
5072                         assert (!_meter->display_to_user ());
5073                         new_processors.insert (amp, _meter);
5074                         break;
5075                 case MeterPostFader:
5076                         /* do nothing here */
5077                         break;
5078                 case MeterOutput:
5079                         /* do nothing here */
5080                         break;
5081                 case MeterCustom:
5082                         /* the meter is visible, so we don't touch it here */
5083                         break;
5084                 }
5085         }
5086
5087         /* MAIN OUTS */
5088
5089         assert (_main_outs);
5090         assert (!_main_outs->display_to_user ());
5091         new_processors.push_back (_main_outs);
5092
5093         /* iterator for the main outs */
5094
5095         ProcessorList::iterator main = new_processors.end();
5096         --main;
5097
5098         /* OUTPUT METERING */
5099
5100         if (_meter && (_meter_point == MeterOutput || _meter_point == MeterPostFader)) {
5101                 assert (!_meter->display_to_user ());
5102
5103                 /* add the processor just before or just after the main outs */
5104
5105                 ProcessorList::iterator meter_point = main;
5106
5107                 if (_meter_point == MeterOutput) {
5108                         ++meter_point;
5109                 }
5110                 new_processors.insert (meter_point, _meter);
5111         }
5112
5113         /* MONITOR SEND */
5114
5115         if (_monitor_send && !is_monitor ()) {
5116                 assert (!_monitor_send->display_to_user ());
5117                 switch (Config->get_listen_position ()) {
5118                 case PreFaderListen:
5119                         switch (Config->get_pfl_position ()) {
5120                         case PFLFromBeforeProcessors:
5121                                 new_processors.push_front (_monitor_send);
5122                                 break;
5123                         case PFLFromAfterProcessors:
5124                                 new_processors.insert (amp, _monitor_send);
5125                                 break;
5126                         }
5127                         _monitor_send->set_can_pan (false);
5128                         break;
5129                 case AfterFaderListen:
5130                         switch (Config->get_afl_position ()) {
5131                         case AFLFromBeforeProcessors:
5132                                 new_processors.insert (after_amp, _monitor_send);
5133                                 break;
5134                         case AFLFromAfterProcessors:
5135                                 new_processors.insert (new_processors.end(), _monitor_send);
5136                                 break;
5137                         }
5138                         _monitor_send->set_can_pan (true);
5139                         break;
5140                 }
5141         }
5142
5143 #if 0 // not used - just yet
5144         if (!is_master() && !is_monitor() && !is_auditioner()) {
5145                 new_processors.push_front (_delayline);
5146         }
5147 #endif
5148
5149         /* MONITOR CONTROL */
5150
5151         if (_monitor_control && is_monitor ()) {
5152                 assert (!_monitor_control->display_to_user ());
5153                 new_processors.insert (amp, _monitor_control);
5154         }
5155
5156         /* INTERNAL RETURN */
5157
5158         /* doing this here means that any monitor control will come just after
5159            the return.
5160         */
5161
5162         if (_intreturn) {
5163                 assert (!_intreturn->display_to_user ());
5164                 new_processors.push_front (_intreturn);
5165         }
5166
5167         if (_trim && _trim->active()) {
5168                 assert (!_trim->display_to_user ());
5169                 new_processors.push_front (_trim);
5170         }
5171         /* EXPORT PROCESSOR */
5172
5173         if (_capturing_processor) {
5174                 assert (!_capturing_processor->display_to_user ());
5175                 new_processors.push_front (_capturing_processor);
5176         }
5177
5178         _processors = new_processors;
5179
5180         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5181                 if (!(*i)->display_to_user () && !(*i)->active () && (*i) != _monitor_send) {
5182                         (*i)->activate ();
5183                 }
5184         }
5185
5186         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: setup_invisible_processors\n", _name));
5187         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5188                 DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1\n", (*i)->name ()));
5189         }
5190 }
5191
5192 void
5193 Route::unpan ()
5194 {
5195         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
5196         Glib::Threads::RWLock::ReaderLock lp (_processor_lock);
5197
5198         _pannable.reset ();
5199
5200         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5201                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery>(*i);
5202                 if (d) {
5203                         d->unpan ();
5204                 }
5205         }
5206 }
5207
5208 /** If the meter point is `Custom', make a note of where the meter is.
5209  *  This is so that if the meter point is subsequently set to something else,
5210  *  and then back to custom, we can put the meter back where it was last time
5211  *  custom was enabled.
5212  *
5213  *  Must be called with the _processor_lock held.
5214  */
5215 void
5216 Route::maybe_note_meter_position ()
5217 {
5218         if (_meter_point != MeterCustom) {
5219                 return;
5220         }
5221
5222         _custom_meter_position_noted = true;
5223         /* custom meter points range from after trim to before panner/main_outs
5224          * this is a limitation by the current processor UI
5225          */
5226         bool seen_trim = false;
5227         _processor_after_last_custom_meter.reset();
5228         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5229                 if ((*i) == _trim) {
5230                         seen_trim = true;
5231                 }
5232                 if ((*i) == _main_outs) {
5233                         _processor_after_last_custom_meter = *i;
5234                         break;
5235                 }
5236                 if (boost::dynamic_pointer_cast<PeakMeter> (*i)) {
5237                         if (!seen_trim) {
5238                                 _processor_after_last_custom_meter = _trim;
5239                         } else {
5240                                 ProcessorList::iterator j = i;
5241                                 ++j;
5242                                 assert(j != _processors.end ()); // main_outs should be before
5243                                 _processor_after_last_custom_meter = *j;
5244                         }
5245                         break;
5246                 }
5247         }
5248         assert(_processor_after_last_custom_meter.lock());
5249 }
5250
5251 boost::shared_ptr<Processor>
5252 Route::processor_by_id (PBD::ID id) const
5253 {
5254         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5255         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5256                 if ((*i)->id() == id) {
5257                         return *i;
5258                 }
5259         }
5260
5261         return boost::shared_ptr<Processor> ();
5262 }
5263
5264 /** @return the monitoring state, or in other words what data we are pushing
5265  *  into the route (data from the inputs, data from disk or silence)
5266  */
5267 MonitorState
5268 Route::monitoring_state () const
5269 {
5270         return MonitoringInput;
5271 }
5272
5273 /** @return what we should be metering; either the data coming from the input
5274  *  IO or the data that is flowing through the route.
5275  */
5276 MeterState
5277 Route::metering_state () const
5278 {
5279         return MeteringRoute;
5280 }
5281
5282 bool
5283 Route::has_external_redirects () const
5284 {
5285         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5286
5287                 /* ignore inactive processors and obviously ignore the main
5288                  * outs since everything has them and we don't care.
5289                  */
5290
5291                 if ((*i)->active() && (*i) != _main_outs && (*i)->does_routing()) {
5292                         return true;;
5293                 }
5294         }
5295
5296         return false;
5297 }
5298
5299 boost::shared_ptr<Processor>
5300 Route::the_instrument () const
5301 {
5302         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5303         return the_instrument_unlocked ();
5304 }
5305
5306 boost::shared_ptr<Processor>
5307 Route::the_instrument_unlocked () const
5308 {
5309         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5310                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*i);
5311                 if (pi && pi->plugin ()->get_info ()->is_instrument ()) {
5312                         return (*i);
5313                 }
5314         }
5315         return boost::shared_ptr<Processor>();
5316 }
5317
5318
5319
5320 void
5321 Route::non_realtime_locate (framepos_t pos)
5322 {
5323         if (_pannable) {
5324                 _pannable->transport_located (pos);
5325         }
5326
5327         if (_delayline.get()) {
5328                 _delayline.get()->flush();
5329         }
5330
5331         {
5332                 //Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
5333                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5334
5335                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5336                         (*i)->transport_located (pos);
5337                 }
5338         }
5339         _roll_delay = _initial_delay;
5340 }
5341
5342 void
5343 Route::fill_buffers_with_input (BufferSet& bufs, boost::shared_ptr<IO> io, pframes_t nframes)
5344 {
5345         size_t n_buffers;
5346         size_t i;
5347
5348         /* MIDI
5349          *
5350          * We don't currently mix MIDI input together, so we don't need the
5351          * complex logic of the audio case.
5352          */
5353
5354         n_buffers = bufs.count().n_midi ();
5355
5356         for (i = 0; i < n_buffers; ++i) {
5357
5358                 boost::shared_ptr<MidiPort> source_port = io->midi (i);
5359                 MidiBuffer& buf (bufs.get_midi (i));
5360
5361                 if (source_port) {
5362                         buf.copy (source_port->get_midi_buffer(nframes));
5363                 } else {
5364                         buf.silence (nframes);
5365                 }
5366         }
5367
5368         /* AUDIO */
5369
5370         n_buffers = bufs.count().n_audio();
5371
5372         size_t n_ports = io->n_ports().n_audio();
5373         float scaling = 1.0f;
5374
5375         if (n_ports > n_buffers) {
5376                 scaling = ((float) n_buffers) / n_ports;
5377         }
5378
5379         for (i = 0; i < n_ports; ++i) {
5380
5381                 /* if there are more ports than buffers, map them onto buffers
5382                  * in a round-robin fashion
5383                  */
5384
5385                 boost::shared_ptr<AudioPort> source_port = io->audio (i);
5386                 AudioBuffer& buf (bufs.get_audio (i%n_buffers));
5387
5388
5389                 if (i < n_buffers) {
5390
5391                         /* first time through just copy a channel into
5392                            the output buffer.
5393                         */
5394
5395                         buf.read_from (source_port->get_audio_buffer (nframes), nframes);
5396
5397                         if (scaling != 1.0f) {
5398                                 buf.apply_gain (scaling, nframes);
5399                         }
5400
5401                 } else {
5402
5403                         /* on subsequent times around, merge data from
5404                          * the port with what is already there
5405                          */
5406
5407                         if (scaling != 1.0f) {
5408                                 buf.accumulate_with_gain_from (source_port->get_audio_buffer (nframes), nframes, 0, scaling);
5409                         } else {
5410                                 buf.accumulate_from (source_port->get_audio_buffer (nframes), nframes);
5411                         }
5412                 }
5413         }
5414
5415         /* silence any remaining buffers */
5416
5417         for (; i < n_buffers; ++i) {
5418                 AudioBuffer& buf (bufs.get_audio (i));
5419                 buf.silence (nframes);
5420         }
5421
5422         /* establish the initial setup of the buffer set, reflecting what was
5423            copied into it. unless, of course, we are the auditioner, in which
5424            case nothing was fed into it from the inputs at all.
5425         */
5426
5427         if (!is_auditioner()) {
5428                 bufs.set_count (io->n_ports());
5429         }
5430 }
5431
5432 boost::shared_ptr<AutomationControl>
5433 Route::pan_azimuth_control() const
5434 {
5435 #ifdef MIXBUS
5436         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5437         if (!plug) {
5438                 return boost::shared_ptr<AutomationControl>();
5439         }
5440         const uint32_t port_channel_post_pan = 2; // gtk2_ardour/mixbus_ports.h
5441         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_channel_post_pan)));
5442 #else
5443         if (!_pannable || !panner()) {
5444                 return boost::shared_ptr<AutomationControl>();
5445         }
5446         return _pannable->pan_azimuth_control;
5447 #endif
5448 }
5449
5450 boost::shared_ptr<AutomationControl>
5451 Route::pan_elevation_control() const
5452 {
5453         if (Profile->get_mixbus() || !_pannable || !panner()) {
5454                 return boost::shared_ptr<AutomationControl>();
5455         }
5456
5457         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5458
5459         if (c.find (PanElevationAutomation) != c.end()) {
5460                 return _pannable->pan_elevation_control;
5461         } else {
5462                 return boost::shared_ptr<AutomationControl>();
5463         }
5464 }
5465 boost::shared_ptr<AutomationControl>
5466 Route::pan_width_control() const
5467 {
5468         if (Profile->get_mixbus() || !_pannable || !panner()) {
5469                 return boost::shared_ptr<AutomationControl>();
5470         }
5471
5472         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5473
5474         if (c.find (PanWidthAutomation) != c.end()) {
5475                 return _pannable->pan_width_control;
5476         } else {
5477                 return boost::shared_ptr<AutomationControl>();
5478         }
5479 }
5480 boost::shared_ptr<AutomationControl>
5481 Route::pan_frontback_control() const
5482 {
5483         if (Profile->get_mixbus() || !_pannable || !panner()) {
5484                 return boost::shared_ptr<AutomationControl>();
5485         }
5486
5487         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5488
5489         if (c.find (PanFrontBackAutomation) != c.end()) {
5490                 return _pannable->pan_frontback_control;
5491         } else {
5492                 return boost::shared_ptr<AutomationControl>();
5493         }
5494 }
5495 boost::shared_ptr<AutomationControl>
5496 Route::pan_lfe_control() const
5497 {
5498         if (Profile->get_mixbus() || !_pannable || !panner()) {
5499                 return boost::shared_ptr<AutomationControl>();
5500         }
5501
5502         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5503
5504         if (c.find (PanLFEAutomation) != c.end()) {
5505                 return _pannable->pan_lfe_control;
5506         } else {
5507                 return boost::shared_ptr<AutomationControl>();
5508         }
5509 }
5510
5511 uint32_t
5512 Route::eq_band_cnt () const
5513 {
5514         if (Profile->get_mixbus()) {
5515                 return 3;
5516         } else {
5517                 /* Ardour has no well-known EQ object */
5518                 return 0;
5519         }
5520 }
5521
5522 boost::shared_ptr<AutomationControl>
5523 Route::eq_gain_controllable (uint32_t band) const
5524 {
5525 #ifdef MIXBUS
5526         boost::shared_ptr<PluginInsert> eq = ch_eq();
5527
5528         if (!eq) {
5529                 return boost::shared_ptr<AutomationControl>();
5530         }
5531
5532         uint32_t port_number;
5533         switch (band) {
5534         case 0:
5535                 if (is_master() || mixbus()) {
5536                         port_number = 4;
5537                 } else {
5538                         port_number = 8;
5539                 }
5540                 break;
5541         case 1:
5542                 if (is_master() || mixbus()) {
5543                         port_number = 3;
5544                 } else {
5545                         port_number = 6;
5546                 }
5547                 break;
5548         case 2:
5549                 if (is_master() || mixbus()) {
5550                         port_number = 2;
5551                 } else {
5552                         port_number = 4;
5553                 }
5554                 break;
5555         default:
5556                 return boost::shared_ptr<AutomationControl>();
5557         }
5558
5559         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_number)));
5560 #else
5561         return boost::shared_ptr<AutomationControl>();
5562 #endif
5563 }
5564 boost::shared_ptr<AutomationControl>
5565 Route::eq_freq_controllable (uint32_t band) const
5566 {
5567 #ifdef MIXBUS
5568
5569         if (mixbus() || is_master()) {
5570                 /* no frequency controls for mixbusses or master */
5571                 return boost::shared_ptr<AutomationControl>();
5572         }
5573
5574         boost::shared_ptr<PluginInsert> eq = ch_eq();
5575
5576         if (!eq) {
5577                 return boost::shared_ptr<AutomationControl>();
5578         }
5579
5580         uint32_t port_number;
5581         switch (band) {
5582         case 0:
5583                 port_number = 7;
5584                 break;
5585         case 1:
5586                 port_number = 5;
5587                 break;
5588         case 2:
5589                 port_number = 3;
5590                 break;
5591         default:
5592                 return boost::shared_ptr<AutomationControl>();
5593         }
5594
5595         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_number)));
5596 #else
5597         return boost::shared_ptr<AutomationControl>();
5598 #endif
5599 }
5600
5601 boost::shared_ptr<AutomationControl>
5602 Route::eq_q_controllable (uint32_t band) const
5603 {
5604         return boost::shared_ptr<AutomationControl>();
5605 }
5606
5607 boost::shared_ptr<AutomationControl>
5608 Route::eq_shape_controllable (uint32_t band) const
5609 {
5610         return boost::shared_ptr<AutomationControl>();
5611 }
5612
5613 boost::shared_ptr<AutomationControl>
5614 Route::eq_enable_controllable () const
5615 {
5616 #ifdef MIXBUS
5617         boost::shared_ptr<PluginInsert> eq = ch_eq();
5618
5619         if (!eq) {
5620                 return boost::shared_ptr<AutomationControl>();
5621         }
5622
5623         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 1)));
5624 #else
5625         return boost::shared_ptr<AutomationControl>();
5626 #endif
5627 }
5628
5629 boost::shared_ptr<AutomationControl>
5630 Route::eq_hpf_controllable () const
5631 {
5632 #ifdef MIXBUS
5633         boost::shared_ptr<PluginInsert> eq = ch_eq();
5634
5635         if (!eq) {
5636                 return boost::shared_ptr<AutomationControl>();
5637         }
5638
5639         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 2)));
5640 #else
5641         return boost::shared_ptr<AutomationControl>();
5642 #endif
5643 }
5644
5645 string
5646 Route::eq_band_name (uint32_t band) const
5647 {
5648         if (Profile->get_mixbus()) {
5649                 switch (band) {
5650                 case 0:
5651                         return _("lo");
5652                 case 1:
5653                         return _("mid");
5654                 case 2:
5655                         return _("hi");
5656                 default:
5657                         return string();
5658                 }
5659         } else {
5660                 return string ();
5661         }
5662 }
5663
5664 boost::shared_ptr<AutomationControl>
5665 Route::comp_enable_controllable () const
5666 {
5667 #ifdef MIXBUS
5668         boost::shared_ptr<PluginInsert> comp = ch_comp();
5669
5670         if (!comp) {
5671                 return boost::shared_ptr<AutomationControl>();
5672         }
5673
5674         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 1)));
5675 #else
5676         return boost::shared_ptr<AutomationControl>();
5677 #endif
5678 }
5679 boost::shared_ptr<AutomationControl>
5680 Route::comp_threshold_controllable () const
5681 {
5682 #ifdef MIXBUS
5683         boost::shared_ptr<PluginInsert> comp = ch_comp();
5684
5685         if (!comp) {
5686                 return boost::shared_ptr<AutomationControl>();
5687         }
5688
5689         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 2)));
5690
5691 #else
5692         return boost::shared_ptr<AutomationControl>();
5693 #endif
5694 }
5695 boost::shared_ptr<AutomationControl>
5696 Route::comp_speed_controllable () const
5697 {
5698 #ifdef MIXBUS
5699         boost::shared_ptr<PluginInsert> comp = ch_comp();
5700
5701         if (!comp) {
5702                 return boost::shared_ptr<AutomationControl>();
5703         }
5704
5705         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 3)));
5706 #else
5707         return boost::shared_ptr<AutomationControl>();
5708 #endif
5709 }
5710 boost::shared_ptr<AutomationControl>
5711 Route::comp_mode_controllable () const
5712 {
5713 #ifdef MIXBUS
5714         boost::shared_ptr<PluginInsert> comp = ch_comp();
5715
5716         if (!comp) {
5717                 return boost::shared_ptr<AutomationControl>();
5718         }
5719
5720         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 4)));
5721 #else
5722         return boost::shared_ptr<AutomationControl>();
5723 #endif
5724 }
5725 boost::shared_ptr<AutomationControl>
5726 Route::comp_makeup_controllable () const
5727 {
5728 #ifdef MIXBUS
5729         boost::shared_ptr<PluginInsert> comp = ch_comp();
5730
5731         if (!comp) {
5732                 return boost::shared_ptr<AutomationControl>();
5733         }
5734
5735         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 5)));
5736 #else
5737         return boost::shared_ptr<AutomationControl>();
5738 #endif
5739 }
5740 boost::shared_ptr<AutomationControl>
5741 Route::comp_redux_controllable () const
5742 {
5743 #ifdef MIXBUS
5744         boost::shared_ptr<PluginInsert> comp = ch_comp();
5745
5746         if (!comp) {
5747                 return boost::shared_ptr<AutomationControl>();
5748         }
5749
5750         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 6)));
5751 #else
5752         return boost::shared_ptr<AutomationControl>();
5753 #endif
5754 }
5755
5756 string
5757 Route::comp_mode_name (uint32_t mode) const
5758 {
5759 #ifdef MIXBUS
5760         switch (mode) {
5761         case 0:
5762                 return _("Leveler");
5763         case 1:
5764                 return _("Compressor");
5765         case 2:
5766                 return _("Limiter");
5767         case 3:
5768                 return mixbus() ? _("Sidechain") : _("Limiter");
5769         }
5770
5771         return _("???");
5772 #else
5773         return _("???");
5774 #endif
5775 }
5776
5777 string
5778 Route::comp_speed_name (uint32_t mode) const
5779 {
5780 #ifdef MIXBUS
5781         switch (mode) {
5782         case 0:
5783                 return _("Attk");
5784         case 1:
5785                 return _("Ratio");
5786         case 2:
5787         case 3:
5788                 return _("Rels");
5789         }
5790         return _("???");
5791 #else
5792         return _("???");
5793 #endif
5794 }
5795
5796 boost::shared_ptr<AutomationControl>
5797 Route::send_level_controllable (uint32_t n) const
5798 {
5799 #ifdef  MIXBUS
5800         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5801         if (!plug) {
5802                 return boost::shared_ptr<AutomationControl>();
5803         }
5804
5805         if (n >= 8) {
5806                 /* no such bus */
5807                 return boost::shared_ptr<AutomationControl>();
5808         }
5809
5810         const uint32_t port_id = port_channel_post_aux1_level + (2*n); // gtk2_ardour/mixbus_ports.h
5811         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_id)));
5812 #else
5813         boost::shared_ptr<Send> s = boost::dynamic_pointer_cast<Send>(nth_send (n));
5814         if (!s) {
5815                 return boost::shared_ptr<AutomationControl>();
5816         }
5817         return s->gain_control ();
5818 #endif
5819 }
5820
5821 boost::shared_ptr<AutomationControl>
5822 Route::send_enable_controllable (uint32_t n) const
5823 {
5824 #ifdef  MIXBUS
5825         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5826         if (!plug) {
5827                 return boost::shared_ptr<AutomationControl>();
5828         }
5829
5830         if (n >= 8) {
5831                 /* no such bus */
5832                 return boost::shared_ptr<AutomationControl>();
5833         }
5834
5835         const uint32_t port_id = port_channel_post_aux1_asgn + (2*n); // gtk2_ardour/mixbus_ports.h
5836         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_id)));
5837 #else
5838         /* although Ardour sends have enable/disable as part of the Processor
5839            API, it is not exposed as a controllable.
5840
5841            XXX: we should fix this.
5842         */
5843         return boost::shared_ptr<AutomationControl>();
5844 #endif
5845 }
5846
5847 string
5848 Route::send_name (uint32_t n) const
5849 {
5850 #ifdef MIXBUS
5851         if (n >= 8) {
5852                 return string();
5853         }
5854         boost::shared_ptr<Route> r = _session.get_mixbus (n);
5855         assert (r);
5856         return r->name();
5857 #else
5858         boost::shared_ptr<Processor> p = nth_send (n);
5859         if (p) {
5860                 return p->name();
5861         } else {
5862                 return string();
5863         }
5864 #endif
5865 }
5866
5867 boost::shared_ptr<AutomationControl>
5868 Route::master_send_enable_controllable () const
5869 {
5870 #ifdef  MIXBUS
5871         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5872         if (!plug) {
5873                 return boost::shared_ptr<AutomationControl>();
5874         }
5875         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_channel_post_mstr_assign)));
5876 #else
5877         return boost::shared_ptr<AutomationControl>();
5878 #endif
5879 }