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