some strategic documentation
[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         return 0;
1343 }
1344
1345 bool
1346 Route::add_processor_from_xml_2X (const XMLNode& node, int version)
1347 {
1348         const XMLProperty *prop;
1349
1350         try {
1351                 boost::shared_ptr<Processor> processor;
1352
1353                 /* bit of a hack: get the `placement' property from the <Redirect> tag here
1354                    so that we can add the processor in the right place (pre/post-fader)
1355                 */
1356
1357                 XMLNodeList const & children = node.children ();
1358                 XMLNodeList::const_iterator i = children.begin ();
1359
1360                 while (i != children.end() && (*i)->name() != X_("Redirect")) {
1361                         ++i;
1362                 }
1363
1364                 Placement placement = PreFader;
1365
1366                 if (i != children.end()) {
1367                         if ((prop = (*i)->property (X_("placement"))) != 0) {
1368                                 placement = Placement (string_2_enum (prop->value(), placement));
1369                         }
1370                 }
1371
1372                 if (node.name() == "Insert") {
1373
1374                         if ((prop = node.property ("type")) != 0) {
1375
1376                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" ||
1377                                                 prop->value() == "lv2" ||
1378                                                 prop->value() == "windows-vst" ||
1379                                                 prop->value() == "lxvst" ||
1380                                                 prop->value() == "audiounit") {
1381
1382                                         if (_session.get_disable_all_loaded_plugins ()) {
1383                                                 processor.reset (new UnknownProcessor (_session, node));
1384                                         } else {
1385                                                 processor.reset (new PluginInsert (_session));
1386                                                 processor->set_owner (this);
1387                                         }
1388
1389                                 } else {
1390
1391                                         processor.reset (new PortInsert (_session, _pannable, _mute_master));
1392                                 }
1393
1394                         }
1395
1396                 } else if (node.name() == "Send") {
1397
1398                         boost::shared_ptr<Pannable> sendpan (new Pannable (_session));
1399                         processor.reset (new Send (_session, sendpan, _mute_master));
1400
1401                 } else {
1402
1403                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), node.name()) << endmsg;
1404                         return false;
1405                 }
1406
1407                 if (processor->set_state (node, version)) {
1408                         return false;
1409                 }
1410
1411                 //A2 uses the "active" flag in the toplevel redirect node, not in the child plugin/IO
1412                 if (i != children.end()) {
1413                         if ((prop = (*i)->property (X_("active"))) != 0) {
1414                                 if ( string_is_affirmative (prop->value()) && (!_session.get_bypass_all_loaded_plugins () || !processor->display_to_user () ) )
1415                                         processor->activate();
1416                                 else
1417                                         processor->deactivate();
1418                         }
1419                 }
1420
1421                 return (add_processor (processor, placement, 0, false) == 0);
1422         }
1423
1424         catch (failed_constructor &err) {
1425                 warning << _("processor could not be created. Ignored.") << endmsg;
1426                 return false;
1427         }
1428 }
1429
1430 int
1431 Route::add_processors (const ProcessorList& others, boost::shared_ptr<Processor> before, ProcessorStreams* err)
1432 {
1433         /* NOTE: this is intended to be used ONLY when copying
1434            processors from another Route. Hence the subtle
1435            differences between this and ::add_processor()
1436         */
1437
1438         ProcessorList::iterator loc;
1439
1440         if (before) {
1441                 loc = find(_processors.begin(), _processors.end(), before);
1442         } else {
1443                 /* nothing specified - at end */
1444                 loc = _processors.end ();
1445         }
1446
1447         if (!_session.engine().connected()) {
1448                 return 1;
1449         }
1450
1451         if (others.empty()) {
1452                 return 0;
1453         }
1454
1455         {
1456                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1457                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1458                 ProcessorState pstate (this);
1459
1460                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
1461
1462                         if (*i == _meter) {
1463                                 continue;
1464                         }
1465
1466                         boost::shared_ptr<PluginInsert> pi;
1467
1468                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1469                                 pi->set_count (1); // why? configure_processors_unlocked() will re-do this
1470                                 pi->set_strict_io (_strict_io);
1471                         }
1472
1473                         _processors.insert (loc, *i);
1474                         (*i)->set_owner (this);
1475
1476                         if ((*i)->active()) {
1477                                 (*i)->activate ();
1478                         }
1479
1480                         /* Think: does this really need to be called for every processor in the loop? */
1481                         {
1482                                 if (configure_processors_unlocked (err)) {
1483                                         pstate.restore ();
1484                                         configure_processors_unlocked (0); // it worked before we tried to add it ...
1485                                         return -1;
1486                                 }
1487                         }
1488
1489                         (*i)->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false));
1490                 }
1491
1492                 for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
1493                         boost::shared_ptr<PluginInsert> pi;
1494
1495                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1496                                 if (pi->has_no_inputs ()) {
1497                                         _have_internal_generator = true;
1498                                         break;
1499                                 }
1500                         }
1501                 }
1502
1503                 _output->set_user_latency (0);
1504         }
1505
1506         reset_instrument_info ();
1507         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1508         set_processor_positions ();
1509
1510         return 0;
1511 }
1512
1513 void
1514 Route::placement_range(Placement p, ProcessorList::iterator& start, ProcessorList::iterator& end)
1515 {
1516         if (p == PreFader) {
1517                 start = _processors.begin();
1518                 end = find(_processors.begin(), _processors.end(), _amp);
1519         } else {
1520                 start = find(_processors.begin(), _processors.end(), _amp);
1521                 ++start;
1522                 end = _processors.end();
1523         }
1524 }
1525
1526 /** Turn off all processors with a given placement
1527  * @param p Placement of processors to disable
1528  */
1529 void
1530 Route::disable_processors (Placement p)
1531 {
1532         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1533
1534         ProcessorList::iterator start, end;
1535         placement_range(p, start, end);
1536
1537         for (ProcessorList::iterator i = start; i != end; ++i) {
1538                 (*i)->deactivate ();
1539         }
1540
1541         _session.set_dirty ();
1542 }
1543
1544 /** Turn off all redirects
1545  */
1546 void
1547 Route::disable_processors ()
1548 {
1549         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1550
1551         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1552                 (*i)->deactivate ();
1553         }
1554
1555         _session.set_dirty ();
1556 }
1557
1558 /** Turn off all redirects with a given placement
1559  * @param p Placement of redirects to disable
1560  */
1561 void
1562 Route::disable_plugins (Placement p)
1563 {
1564         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1565
1566         ProcessorList::iterator start, end;
1567         placement_range(p, start, end);
1568
1569         for (ProcessorList::iterator i = start; i != end; ++i) {
1570                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1571                         (*i)->deactivate ();
1572                 }
1573         }
1574
1575         _session.set_dirty ();
1576 }
1577
1578 /** Turn off all plugins
1579  */
1580 void
1581 Route::disable_plugins ()
1582 {
1583         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1584
1585         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1586                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1587                         (*i)->deactivate ();
1588                 }
1589         }
1590
1591         _session.set_dirty ();
1592 }
1593
1594
1595 void
1596 Route::ab_plugins (bool forward)
1597 {
1598         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
1599
1600         if (forward) {
1601
1602                 /* forward = turn off all active redirects, and mark them so that the next time
1603                    we go the other way, we will revert them
1604                 */
1605
1606                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1607                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1608                                 continue;
1609                         }
1610
1611                         if ((*i)->active()) {
1612                                 (*i)->deactivate ();
1613                                 (*i)->set_next_ab_is_active (true);
1614                         } else {
1615                                 (*i)->set_next_ab_is_active (false);
1616                         }
1617                 }
1618
1619         } else {
1620
1621                 /* backward = if the redirect was marked to go active on the next ab, do so */
1622
1623                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1624
1625                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1626                                 continue;
1627                         }
1628
1629                         if ((*i)->get_next_ab_is_active()) {
1630                                 (*i)->activate ();
1631                         } else {
1632                                 (*i)->deactivate ();
1633                         }
1634                 }
1635         }
1636
1637         _session.set_dirty ();
1638 }
1639
1640
1641 /** Remove processors with a given placement.
1642  * @param p Placement of processors to remove.
1643  */
1644 void
1645 Route::clear_processors (Placement p)
1646 {
1647         if (!_session.engine().connected()) {
1648                 return;
1649         }
1650
1651         bool already_deleting = _session.deletion_in_progress();
1652         if (!already_deleting) {
1653                 _session.set_deletion_in_progress();
1654         }
1655
1656         {
1657                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1658                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1659                 ProcessorList new_list;
1660                 ProcessorStreams err;
1661                 bool seen_amp = false;
1662
1663                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1664
1665                         if (*i == _amp) {
1666                                 seen_amp = true;
1667                         }
1668
1669                         if ((*i) == _amp || (*i) == _meter || (*i) == _main_outs || (*i) == _delayline || (*i) == _trim) {
1670
1671                                 /* you can't remove these */
1672
1673                                 new_list.push_back (*i);
1674
1675                         } else {
1676                                 if (seen_amp) {
1677
1678                                         switch (p) {
1679                                         case PreFader:
1680                                                 new_list.push_back (*i);
1681                                                 break;
1682                                         case PostFader:
1683                                                 (*i)->drop_references ();
1684                                                 break;
1685                                         }
1686
1687                                 } else {
1688
1689                                         switch (p) {
1690                                         case PreFader:
1691                                                 (*i)->drop_references ();
1692                                                 break;
1693                                         case PostFader:
1694                                                 new_list.push_back (*i);
1695                                                 break;
1696                                         }
1697                                 }
1698                         }
1699                 }
1700
1701                 _processors = new_list;
1702                 configure_processors_unlocked (&err); // this can't fail
1703         }
1704
1705         processor_max_streams.reset();
1706         _have_internal_generator = false;
1707         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1708         set_processor_positions ();
1709
1710         reset_instrument_info ();
1711
1712         if (!already_deleting) {
1713                 _session.clear_deletion_in_progress();
1714         }
1715 }
1716
1717 int
1718 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err, bool need_process_lock)
1719 {
1720         // TODO once the export point can be configured properly, do something smarter here
1721         if (processor == _capturing_processor) {
1722                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1723                 if (need_process_lock) {
1724                         lx.acquire();
1725                 }
1726
1727                 _capturing_processor.reset();
1728
1729                 if (need_process_lock) {
1730                         lx.release();
1731                 }
1732         }
1733
1734         /* these can never be removed */
1735
1736         if (processor == _amp || processor == _meter || processor == _main_outs || processor == _delayline || processor == _trim) {
1737                 return 0;
1738         }
1739
1740         if (!_session.engine().connected()) {
1741                 return 1;
1742         }
1743
1744         processor_max_streams.reset();
1745
1746         {
1747                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1748                 if (need_process_lock) {
1749                         lx.acquire();
1750                 }
1751
1752                 /* Caller must hold process lock */
1753                 assert (!AudioEngine::instance()->process_lock().trylock());
1754
1755                 Glib::Threads::RWLock::WriterLock lm (_processor_lock); // XXX deadlock after export
1756
1757                 ProcessorState pstate (this);
1758
1759                 ProcessorList::iterator i;
1760                 bool removed = false;
1761
1762                 for (i = _processors.begin(); i != _processors.end(); ) {
1763                         if (*i == processor) {
1764
1765                                 /* move along, see failure case for configure_processors()
1766                                    where we may need to reconfigure the processor.
1767                                 */
1768
1769                                 /* stop redirects that send signals to JACK ports
1770                                    from causing noise as a result of no longer being
1771                                    run.
1772                                 */
1773
1774                                 boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor> (*i);
1775                                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*i);
1776
1777                                 if (pi != 0) {
1778                                         assert (iop == 0);
1779                                         iop = pi->sidechain();
1780                                 }
1781
1782                                 if (iop != 0) {
1783                                         iop->disconnect ();
1784                                 }
1785
1786                                 i = _processors.erase (i);
1787                                 removed = true;
1788                                 break;
1789
1790                         } else {
1791                                 ++i;
1792                         }
1793
1794                         _output->set_user_latency (0);
1795                 }
1796
1797                 if (!removed) {
1798                         /* what? */
1799                         return 1;
1800                 }
1801
1802                 if (configure_processors_unlocked (err)) {
1803                         pstate.restore ();
1804                         /* we know this will work, because it worked before :) */
1805                         configure_processors_unlocked (0);
1806                         return -1;
1807                 }
1808
1809                 _have_internal_generator = false;
1810
1811                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1812                         boost::shared_ptr<PluginInsert> pi;
1813
1814                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1815                                 if (pi->has_no_inputs ()) {
1816                                         _have_internal_generator = true;
1817                                         break;
1818                                 }
1819                         }
1820                 }
1821                 if (need_process_lock) {
1822                         lx.release();
1823                 }
1824         }
1825
1826         reset_instrument_info ();
1827         processor->drop_references ();
1828         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1829         set_processor_positions ();
1830
1831         return 0;
1832 }
1833
1834 int
1835 Route::replace_processor (boost::shared_ptr<Processor> old, boost::shared_ptr<Processor> sub, ProcessorStreams* err)
1836 {
1837         /* these can never be removed */
1838         if (old == _amp || old == _meter || old == _main_outs || old == _delayline || old == _trim) {
1839                 return 1;
1840         }
1841         /* and can't be used as substitute, either */
1842         if (sub == _amp || sub == _meter || sub == _main_outs || sub == _delayline || sub == _trim) {
1843                 return 1;
1844         }
1845
1846         /* I/Os are out, too */
1847         if (boost::dynamic_pointer_cast<IOProcessor> (old) || boost::dynamic_pointer_cast<IOProcessor> (sub)) {
1848                 return 1;
1849         }
1850
1851         /* this function cannot be used to swap/reorder processors */
1852         if (find (_processors.begin(), _processors.end(), sub) != _processors.end ()) {
1853                 return 1;
1854         }
1855
1856         if (!AudioEngine::instance()->connected() || !old || !sub) {
1857                 return 1;
1858         }
1859
1860         /* ensure that sub is not owned by another route */
1861         if (sub->owner ()) {
1862                 return 1;
1863         }
1864
1865         {
1866                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1867                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1868                 ProcessorState pstate (this);
1869
1870                 assert (find (_processors.begin(), _processors.end(), sub) == _processors.end ());
1871
1872                 ProcessorList::iterator i;
1873                 bool replaced = false;
1874                 bool enable = old->active ();
1875
1876                 for (i = _processors.begin(); i != _processors.end(); ) {
1877                         if (*i == old) {
1878                                 i = _processors.erase (i);
1879                                 _processors.insert (i, sub);
1880                                 sub->set_owner (this);
1881                                 replaced = true;
1882                                 break;
1883                         } else {
1884                                 ++i;
1885                         }
1886                 }
1887
1888                 if (!replaced) {
1889                         return 1;
1890                 }
1891
1892                 if (_strict_io) {
1893                         boost::shared_ptr<PluginInsert> pi;
1894                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(sub)) != 0) {
1895                                 pi->set_strict_io (true);
1896                         }
1897                 }
1898
1899                 if (configure_processors_unlocked (err)) {
1900                         pstate.restore ();
1901                         configure_processors_unlocked (0);
1902                         return -1;
1903                 }
1904
1905                 _have_internal_generator = false;
1906
1907                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1908                         boost::shared_ptr<PluginInsert> pi;
1909                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1910                                 if (pi->has_no_inputs ()) {
1911                                         _have_internal_generator = true;
1912                                         break;
1913                                 }
1914                         }
1915                 }
1916
1917                 if (enable) {
1918                         sub->activate ();
1919                 }
1920
1921                 sub->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false));
1922                 _output->set_user_latency (0);
1923         }
1924
1925         reset_instrument_info ();
1926         old->drop_references ();
1927         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1928         set_processor_positions ();
1929         return 0;
1930 }
1931
1932 int
1933 Route::remove_processors (const ProcessorList& to_be_deleted, ProcessorStreams* err)
1934 {
1935         ProcessorList deleted;
1936
1937         if (!_session.engine().connected()) {
1938                 return 1;
1939         }
1940
1941         processor_max_streams.reset();
1942
1943         {
1944                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
1945                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
1946                 ProcessorState pstate (this);
1947
1948                 ProcessorList::iterator i;
1949                 boost::shared_ptr<Processor> processor;
1950
1951                 for (i = _processors.begin(); i != _processors.end(); ) {
1952
1953                         processor = *i;
1954
1955                         /* these can never be removed */
1956
1957                         if (processor == _amp || processor == _meter || processor == _main_outs || processor == _delayline || processor == _trim) {
1958                                 ++i;
1959                                 continue;
1960                         }
1961
1962                         /* see if its in the list of processors to delete */
1963
1964                         if (find (to_be_deleted.begin(), to_be_deleted.end(), processor) == to_be_deleted.end()) {
1965                                 ++i;
1966                                 continue;
1967                         }
1968
1969                         /* stop IOProcessors that send to JACK ports
1970                            from causing noise as a result of no longer being
1971                            run.
1972                         */
1973
1974                         boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(processor);
1975                         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(processor);
1976                         if (pi != 0) {
1977                                 assert (iop == 0);
1978                                 iop = pi->sidechain();
1979                         }
1980
1981                         if (iop != 0) {
1982                                 iop->disconnect ();
1983                         }
1984
1985                         deleted.push_back (processor);
1986                         i = _processors.erase (i);
1987                 }
1988
1989                 if (deleted.empty()) {
1990                         /* none of those in the requested list were found */
1991                         return 0;
1992                 }
1993
1994                 _output->set_user_latency (0);
1995
1996                 if (configure_processors_unlocked (err)) {
1997                         pstate.restore ();
1998                         /* we know this will work, because it worked before :) */
1999                         configure_processors_unlocked (0);
2000                         return -1;
2001                 }
2002                 //lx.unlock();
2003
2004                 _have_internal_generator = false;
2005
2006                 for (i = _processors.begin(); i != _processors.end(); ++i) {
2007                         boost::shared_ptr<PluginInsert> pi;
2008
2009                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
2010                                 if (pi->has_no_inputs ()) {
2011                                         _have_internal_generator = true;
2012                                         break;
2013                                 }
2014                         }
2015                 }
2016         }
2017
2018         /* now try to do what we need to so that those that were removed will be deleted */
2019
2020         for (ProcessorList::iterator i = deleted.begin(); i != deleted.end(); ++i) {
2021                 (*i)->drop_references ();
2022         }
2023
2024         reset_instrument_info ();
2025         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2026         set_processor_positions ();
2027
2028         return 0;
2029 }
2030
2031 void
2032 Route::reset_instrument_info ()
2033 {
2034         boost::shared_ptr<Processor> instr = the_instrument();
2035         if (instr) {
2036                 _instrument_info.set_internal_instrument (instr);
2037         }
2038 }
2039
2040 /** Caller must hold process lock */
2041 int
2042 Route::configure_processors (ProcessorStreams* err)
2043 {
2044 #ifndef PLATFORM_WINDOWS
2045         assert (!AudioEngine::instance()->process_lock().trylock());
2046 #endif
2047
2048         if (!_in_configure_processors) {
2049                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2050                 return configure_processors_unlocked (err);
2051         }
2052
2053         return 0;
2054 }
2055
2056 ChanCount
2057 Route::input_streams () const
2058 {
2059         return _input->n_ports ();
2060 }
2061
2062 list<pair<ChanCount, ChanCount> >
2063 Route::try_configure_processors (ChanCount in, ProcessorStreams* err)
2064 {
2065         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2066
2067         return try_configure_processors_unlocked (in, err);
2068 }
2069
2070 list<pair<ChanCount, ChanCount> >
2071 Route::try_configure_processors_unlocked (ChanCount in, ProcessorStreams* err)
2072 {
2073         // Check each processor in order to see if we can configure as requested
2074         ChanCount out;
2075         list<pair<ChanCount, ChanCount> > configuration;
2076         uint32_t index = 0;
2077
2078         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configure processors\n", _name));
2079         DEBUG_TRACE (DEBUG::Processors, "{\n");
2080
2081         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++index) {
2082
2083                 if ((*p)->can_support_io_configuration(in, out)) {
2084                         DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1 ID=%2 in=%3 out=%4\n",(*p)->name(), (*p)->id(), in, out));
2085                         configuration.push_back(make_pair(in, out));
2086
2087                         if (is_monitor()) {
2088                                 // restriction for Monitor Section Processors
2089                                 if (in.n_audio() != out.n_audio() || out.n_midi() > 0) {
2090                                         /* do not allow to add/remove channels (for now)
2091                                          * The Monitor follows the master-bus and has no panner (unpan)
2092                                          * but do allow processors with midi-in to be added (e.g VSTs with control that
2093                                          * will remain unconnected)
2094                                          */
2095                                         DEBUG_TRACE (DEBUG::Processors, "Monitor: Channel configuration not allowed.\n");
2096                                         return list<pair<ChanCount, ChanCount> > ();
2097                                 }
2098                                 if (boost::dynamic_pointer_cast<InternalSend> (*p)) {
2099                                         // internal sends make no sense, only feedback
2100                                         DEBUG_TRACE (DEBUG::Processors, "Monitor: No Sends allowed.\n");
2101                                         return list<pair<ChanCount, ChanCount> > ();
2102                                 }
2103                                 if (boost::dynamic_pointer_cast<PortInsert> (*p)) {
2104                                         /* External Sends can be problematic. one can add/remove ports
2105                                          * there signal leaves the DAW to external monitors anyway, so there's
2106                                          * no real use for allowing them here anyway.
2107                                          */
2108                                         DEBUG_TRACE (DEBUG::Processors, "Monitor: No External Sends allowed.\n");
2109                                         return list<pair<ChanCount, ChanCount> > ();
2110                                 }
2111                                 if (boost::dynamic_pointer_cast<Send> (*p)) {
2112                                         // ditto
2113                                         DEBUG_TRACE (DEBUG::Processors, "Monitor: No Sends allowed.\n");
2114                                         return list<pair<ChanCount, ChanCount> > ();
2115                                 }
2116                         }
2117                         in = out;
2118                 } else {
2119                         if (err) {
2120                                 err->index = index;
2121                                 err->count = in;
2122                         }
2123                         DEBUG_TRACE (DEBUG::Processors, "---- CONFIGURATION FAILED.\n");
2124                         DEBUG_TRACE (DEBUG::Processors, string_compose ("---- %1 cannot support in=%2 out=%3\n", (*p)->name(), in, out));
2125                         DEBUG_TRACE (DEBUG::Processors, "}\n");
2126                         return list<pair<ChanCount, ChanCount> > ();
2127                 }
2128         }
2129
2130         DEBUG_TRACE (DEBUG::Processors, "}\n");
2131
2132         return configuration;
2133 }
2134
2135 /** Set the input/output configuration of each processor in the processors list.
2136  *  Caller must hold process lock.
2137  *  Return 0 on success, otherwise configuration is impossible.
2138  */
2139 int
2140 Route::configure_processors_unlocked (ProcessorStreams* err)
2141 {
2142 #ifndef PLATFORM_WINDOWS
2143         assert (!AudioEngine::instance()->process_lock().trylock());
2144 #endif
2145
2146         if (_in_configure_processors) {
2147                 return 0;
2148         }
2149
2150         /* put invisible processors where they should be */
2151         setup_invisible_processors ();
2152
2153         _in_configure_processors = true;
2154
2155         list<pair<ChanCount, ChanCount> > configuration = try_configure_processors_unlocked (input_streams (), err);
2156
2157         if (configuration.empty ()) {
2158                 _in_configure_processors = false;
2159                 return -1;
2160         }
2161
2162         ChanCount out;
2163         bool seen_mains_out = false;
2164         processor_out_streams = _input->n_ports();
2165         processor_max_streams.reset();
2166
2167         list< pair<ChanCount,ChanCount> >::iterator c = configuration.begin();
2168         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++c) {
2169
2170                 if (!(*p)->configure_io(c->first, c->second)) {
2171                         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configuration failed\n", _name));
2172                         _in_configure_processors = false;
2173                         return -1;
2174                 }
2175                 processor_max_streams = ChanCount::max(processor_max_streams, c->first);
2176                 processor_max_streams = ChanCount::max(processor_max_streams, c->second);
2177
2178                 boost::shared_ptr<PluginInsert> pi;
2179                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*p)) != 0) {
2180                         /* plugins connected via Split or Hide Match may have more channels.
2181                          * route/scratch buffers are needed for all of them
2182                          * The configuration may only be a subset (both input and output)
2183                          */
2184                         processor_max_streams = ChanCount::max(processor_max_streams, pi->input_streams());
2185                         processor_max_streams = ChanCount::max(processor_max_streams, pi->internal_streams());
2186                         processor_max_streams = ChanCount::max(processor_max_streams, pi->output_streams());
2187                         processor_max_streams = ChanCount::max(processor_max_streams, pi->natural_input_streams() * pi->get_count());
2188                         processor_max_streams = ChanCount::max(processor_max_streams, pi->natural_output_streams() * pi->get_count());
2189                 }
2190                 out = c->second;
2191
2192                 if (boost::dynamic_pointer_cast<Delivery> (*p)
2193                                 && boost::dynamic_pointer_cast<Delivery> (*p)->role() == Delivery::Main) {
2194                         /* main delivery will increase port count to match input.
2195                          * the Delivery::Main is usually the last processor - followed only by
2196                          * 'MeterOutput'.
2197                          */
2198                         seen_mains_out = true;
2199                 }
2200                 if (!seen_mains_out) {
2201                         processor_out_streams = out;
2202                 }
2203         }
2204
2205
2206         if (_meter) {
2207                 _meter->set_max_channels (processor_max_streams);
2208         }
2209
2210         /* make sure we have sufficient scratch buffers to cope with the new processor
2211            configuration
2212         */
2213         _session.ensure_buffers (n_process_buffers ());
2214
2215         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configuration complete\n", _name));
2216
2217         _in_configure_processors = false;
2218         return 0;
2219 }
2220
2221 /** Set all visible processors to a given active state (except Fader, whose state is not changed)
2222  *  @param state New active state for those processors.
2223  */
2224 void
2225 Route::all_visible_processors_active (bool state)
2226 {
2227         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2228
2229         if (_processors.empty()) {
2230                 return;
2231         }
2232
2233         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2234                 if (!(*i)->display_to_user() || boost::dynamic_pointer_cast<Amp> (*i)) {
2235                         continue;
2236                 }
2237
2238                 if (state) {
2239                         (*i)->activate ();
2240                 } else {
2241                         (*i)->deactivate ();
2242                 }
2243         }
2244
2245         _session.set_dirty ();
2246 }
2247
2248 bool
2249 Route::processors_reorder_needs_configure (const ProcessorList& new_order)
2250 {
2251         /* check if re-order requires re-configuration of any processors
2252          * -> compare channel configuration for all processors
2253          */
2254         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2255         ChanCount c = input_streams ();
2256
2257         for (ProcessorList::const_iterator j = new_order.begin(); j != new_order.end(); ++j) {
2258                 bool found = false;
2259                 if (c != (*j)->input_streams()) {
2260                         return true;
2261                 }
2262                 for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2263                         if (*i == *j) {
2264                                 found = true;
2265                                 if ((*i)->input_streams() != c) {
2266                                         return true;
2267                                 }
2268                                 c = (*i)->output_streams();
2269                                 break;
2270                         }
2271                 }
2272                 if (!found) {
2273                         return true;
2274                 }
2275         }
2276         return false;
2277 }
2278
2279 #ifdef __clang__
2280 __attribute__((annotate("realtime")))
2281 #endif
2282 void
2283 Route::apply_processor_order (const ProcessorList& new_order)
2284 {
2285         /* need to hold processor_lock; either read or write lock
2286          * and the engine process_lock.
2287          * Due to r/w lock ambiguity we can only assert the latter
2288          */
2289         assert (!AudioEngine::instance()->process_lock().trylock());
2290
2291
2292         /* "new_order" is an ordered list of processors to be positioned according to "placement".
2293          * NOTE: all processors in "new_order" MUST be marked as display_to_user(). There maybe additional
2294          * processors in the current actual processor list that are hidden. Any visible processors
2295          *  in the current list but not in "new_order" will be assumed to be deleted.
2296          */
2297
2298         /* "as_it_will_be" and "_processors" are lists of shared pointers.
2299          * actual memory usage is small, but insert/erase is not actually rt-safe :(
2300          * (note though that  ::processors_reorder_needs_configure() ensured that
2301          * this function will only ever be called from the rt-thread if no processor were removed)
2302          *
2303          * either way, I can't proove it, but an x-run due to re-order here is less likley
2304          * than an x-run-less 'ardour-silent cycle' both of which effectively "click".
2305          */
2306
2307         ProcessorList as_it_will_be;
2308         ProcessorList::iterator oiter;
2309         ProcessorList::const_iterator niter;
2310
2311         oiter = _processors.begin();
2312         niter = new_order.begin();
2313
2314         while (niter !=  new_order.end()) {
2315
2316                 /* if the next processor in the old list is invisible (i.e. should not be in the new order)
2317                    then append it to the temp list.
2318
2319                    Otherwise, see if the next processor in the old list is in the new list. if not,
2320                    its been deleted. If its there, append it to the temp list.
2321                    */
2322
2323                 if (oiter == _processors.end()) {
2324
2325                         /* no more elements in the old list, so just stick the rest of
2326                            the new order onto the temp list.
2327                            */
2328
2329                         as_it_will_be.insert (as_it_will_be.end(), niter, new_order.end());
2330                         while (niter != new_order.end()) {
2331                                 ++niter;
2332                         }
2333                         break;
2334
2335                 } else {
2336
2337                         if (!(*oiter)->display_to_user()) {
2338
2339                                 as_it_will_be.push_back (*oiter);
2340
2341                         } else {
2342
2343                                 /* visible processor: check that its in the new order */
2344
2345                                 if (find (new_order.begin(), new_order.end(), (*oiter)) == new_order.end()) {
2346                                         /* deleted: do nothing, shared_ptr<> will clean up */
2347                                 } else {
2348                                         /* ignore this one, and add the next item from the new order instead */
2349                                         as_it_will_be.push_back (*niter);
2350                                         ++niter;
2351                                 }
2352                         }
2353
2354                         /* now remove from old order - its taken care of no matter what */
2355                         oiter = _processors.erase (oiter);
2356                 }
2357
2358         }
2359         _processors.insert (oiter, as_it_will_be.begin(), as_it_will_be.end());
2360
2361         /* If the meter is in a custom position, find it and make a rough note of its position */
2362         maybe_note_meter_position ();
2363 }
2364
2365 int
2366 Route::reorder_processors (const ProcessorList& new_order, ProcessorStreams* err)
2367 {
2368         // it a change is already queued, wait for it
2369         // (unless engine is stopped. apply immediately and proceed
2370         while (g_atomic_int_get (&_pending_process_reorder)) {
2371                 if (!AudioEngine::instance()->running()) {
2372                         DEBUG_TRACE (DEBUG::Processors, "offline apply queued processor re-order.\n");
2373                         Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2374
2375                         apply_processor_order(_pending_processor_order);
2376                         setup_invisible_processors ();
2377
2378                         g_atomic_int_set (&_pending_process_reorder, 0);
2379
2380                         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2381                         set_processor_positions ();
2382                 } else {
2383                         // TODO rather use a semaphore or something.
2384                         // but since ::reorder_processors() is called
2385                         // from the GUI thread, this is fine..
2386                         Glib::usleep(500);
2387                 }
2388         }
2389
2390         if (processors_reorder_needs_configure (new_order) || !AudioEngine::instance()->running()) {
2391
2392                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
2393                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2394                 ProcessorState pstate (this);
2395
2396                 apply_processor_order (new_order);
2397
2398                 if (configure_processors_unlocked (err)) {
2399                         pstate.restore ();
2400                         return -1;
2401                 }
2402
2403                 lm.release();
2404                 lx.release();
2405
2406                 processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2407                 set_processor_positions ();
2408
2409         } else {
2410                 DEBUG_TRACE (DEBUG::Processors, "Queue clickless processor re-order.\n");
2411                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2412
2413                 // _pending_processor_order is protected by _processor_lock
2414                 _pending_processor_order = new_order;
2415                 g_atomic_int_set (&_pending_process_reorder, 1);
2416         }
2417
2418         return 0;
2419 }
2420
2421 bool
2422 Route::add_remove_sidechain (boost::shared_ptr<Processor> proc, bool add)
2423 {
2424         boost::shared_ptr<PluginInsert> pi;
2425         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(proc)) == 0) {
2426                 return false;
2427         }
2428
2429         if (pi->has_sidechain () == add) {
2430                 return true; // ?? call failed, but result is as expected.
2431         }
2432
2433         {
2434                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2435                 ProcessorList::iterator i = find (_processors.begin(), _processors.end(), proc);
2436                 if (i == _processors.end ()) {
2437                         return false;
2438                 }
2439         }
2440
2441         {
2442                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ()); // take before Writerlock to avoid deadlock
2443                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2444                 PBD::Unwinder<bool> uw (_in_sidechain_setup, true);
2445
2446                 lx.release (); // IO::add_port() and ~IO takes process lock  - XXX check if this is safe
2447                 if (add) {
2448                         if (!pi->add_sidechain ()) {
2449                                 return false;
2450                         }
2451                 } else {
2452                         if (!pi->del_sidechain ()) {
2453                                 return false;
2454                         }
2455                 }
2456
2457                 lx.acquire ();
2458                 list<pair<ChanCount, ChanCount> > c = try_configure_processors_unlocked (n_inputs (), 0);
2459                 lx.release ();
2460
2461                 if (c.empty()) {
2462                         if (add) {
2463                                 pi->del_sidechain ();
2464                         } else {
2465                                 pi->add_sidechain ();
2466                                 // TODO restore side-chain's state.
2467                         }
2468                         return false;
2469                 }
2470                 lx.acquire ();
2471                 configure_processors_unlocked (0);
2472         }
2473
2474         if (pi->has_sidechain ()) {
2475                 pi->sidechain_input ()->changed.connect_same_thread (*this, boost::bind (&Route::sidechain_change_handler, this, _1, _2));
2476         }
2477
2478         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2479         _session.set_dirty ();
2480         return true;
2481 }
2482
2483 bool
2484 Route::reset_plugin_insert (boost::shared_ptr<Processor> proc)
2485 {
2486         ChanCount unused;
2487         return customize_plugin_insert (proc, 0, unused);
2488 }
2489
2490 bool
2491 Route::customize_plugin_insert (boost::shared_ptr<Processor> proc, uint32_t count, ChanCount outs)
2492 {
2493         boost::shared_ptr<PluginInsert> pi;
2494         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(proc)) == 0) {
2495                 return false;
2496         }
2497
2498         {
2499                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2500                 ProcessorList::iterator i = find (_processors.begin(), _processors.end(), proc);
2501                 if (i == _processors.end ()) {
2502                         return false;
2503                 }
2504         }
2505
2506         {
2507                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
2508                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
2509
2510                 bool      old_cust = pi->custom_cfg ();
2511                 uint32_t  old_cnt  = pi->get_count ();
2512                 ChanCount old_chan = pi->output_streams ();
2513
2514                 if (count == 0) {
2515                         pi->set_custom_cfg (false);
2516                 } else {
2517                         pi->set_custom_cfg (true);
2518                         pi->set_count (count);
2519                         pi->set_outputs (outs);
2520                 }
2521
2522                 list<pair<ChanCount, ChanCount> > c = try_configure_processors_unlocked (n_inputs (), 0);
2523                 if (c.empty()) {
2524                         /* not possible */
2525
2526                         pi->set_count (old_cnt);
2527                         pi->set_outputs (old_chan);
2528                         pi->set_custom_cfg (old_cust);
2529
2530                         return false;
2531                 }
2532                 configure_processors_unlocked (0);
2533         }
2534
2535         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2536         _session.set_dirty ();
2537         return true;
2538 }
2539
2540 bool
2541 Route::set_strict_io (const bool enable)
2542 {
2543         if (_strict_io != enable) {
2544                 _strict_io = enable;
2545                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2546                 for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p) {
2547                         boost::shared_ptr<PluginInsert> pi;
2548                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*p)) != 0) {
2549                                 pi->set_strict_io (_strict_io);
2550                         }
2551                 }
2552
2553                 list<pair<ChanCount, ChanCount> > c = try_configure_processors_unlocked (n_inputs (), 0);
2554
2555                 if (c.empty()) {
2556                         // not possible
2557                         _strict_io = !enable; // restore old value
2558                         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p) {
2559                                 boost::shared_ptr<PluginInsert> pi;
2560                                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*p)) != 0) {
2561                                         pi->set_strict_io (_strict_io);
2562                                 }
2563                         }
2564                         return false;
2565                 }
2566                 lm.release ();
2567
2568                 {
2569                         Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
2570                         configure_processors (0);
2571                 }
2572                 processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2573                 _session.set_dirty ();
2574         }
2575         return true;
2576 }
2577
2578 XMLNode&
2579 Route::get_state()
2580 {
2581         return state(true);
2582 }
2583
2584 XMLNode&
2585 Route::get_template()
2586 {
2587         return state(false);
2588 }
2589
2590 XMLNode&
2591 Route::state(bool full_state)
2592 {
2593         if (!_session._template_state_dir.empty()) {
2594                 assert (!full_state); // only for templates
2595                 foreach_processor (sigc::bind (sigc::mem_fun (*this, &Route::set_plugin_state_dir), _session._template_state_dir));
2596         }
2597
2598         XMLNode *node = new XMLNode("Route");
2599         ProcessorList::iterator i;
2600         char buf[32];
2601
2602         id().print (buf, sizeof (buf));
2603         node->add_property("id", buf);
2604         node->add_property ("name", _name);
2605         node->add_property("default-type", _default_type.to_string());
2606         node->add_property ("strict-io", _strict_io);
2607
2608         if (_flags) {
2609                 node->add_property("flags", enum_2_string (_flags));
2610         }
2611
2612         node->add_property("active", _active?"yes":"no");
2613         string p;
2614         boost::to_string (_phase_invert, p);
2615         node->add_property("phase-invert", p);
2616         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
2617         node->add_property("meter-point", enum_2_string (_meter_point));
2618
2619         node->add_property("meter-type", enum_2_string (_meter_type));
2620
2621         if (_route_group) {
2622                 node->add_property("route-group", _route_group->name());
2623         }
2624
2625         snprintf (buf, sizeof (buf), "%d", _order_key);
2626         node->add_property ("order-key", buf);
2627         node->add_property ("self-solo", (_self_solo ? "yes" : "no"));
2628         snprintf (buf, sizeof (buf), "%d", _soloed_by_others_upstream);
2629         node->add_property ("soloed-by-upstream", buf);
2630         snprintf (buf, sizeof (buf), "%d", _soloed_by_others_downstream);
2631         node->add_property ("soloed-by-downstream", buf);
2632         node->add_property ("solo-isolated", solo_isolated() ? "yes" : "no");
2633         node->add_property ("solo-safe", _solo_safe ? "yes" : "no");
2634
2635         node->add_child_nocopy (_input->state (full_state));
2636         node->add_child_nocopy (_output->state (full_state));
2637         node->add_child_nocopy (_solo_control->get_state ());
2638         node->add_child_nocopy (_mute_control->get_state ());
2639         node->add_child_nocopy (_mute_master->get_state ());
2640
2641         if (full_state) {
2642                 node->add_child_nocopy (Automatable::get_automation_xml_state ());
2643         }
2644
2645         XMLNode* remote_control_node = new XMLNode (X_("RemoteControl"));
2646         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
2647         remote_control_node->add_property (X_("id"), buf);
2648         node->add_child_nocopy (*remote_control_node);
2649
2650         if (_comment.length()) {
2651                 XMLNode *cmt = node->add_child ("Comment");
2652                 cmt->add_content (_comment);
2653         }
2654
2655         if (_pannable) {
2656                 node->add_child_nocopy (_pannable->state (full_state));
2657         }
2658
2659         for (i = _processors.begin(); i != _processors.end(); ++i) {
2660                 if (!full_state) {
2661                         /* template save: do not include internal sends functioning as
2662                            aux sends because the chance of the target ID
2663                            in the session where this template is used
2664                            is not very likely.
2665
2666                            similarly, do not save listen sends which connect to
2667                            the monitor section, because these will always be
2668                            added if necessary.
2669                         */
2670                         boost::shared_ptr<InternalSend> is;
2671
2672                         if ((is = boost::dynamic_pointer_cast<InternalSend> (*i)) != 0) {
2673                                 if (is->role() == Delivery::Listen) {
2674                                         continue;
2675                                 }
2676                         }
2677                 }
2678                 node->add_child_nocopy((*i)->state (full_state));
2679         }
2680
2681         if (_extra_xml) {
2682                 node->add_child_copy (*_extra_xml);
2683         }
2684
2685         if (_custom_meter_position_noted) {
2686                 boost::shared_ptr<Processor> after = _processor_after_last_custom_meter.lock ();
2687                 if (after) {
2688                         after->id().print (buf, sizeof (buf));
2689                         node->add_property (X_("processor-after-last-custom-meter"), buf);
2690                 }
2691         }
2692
2693         if (!_session._template_state_dir.empty()) {
2694                 foreach_processor (sigc::bind (sigc::mem_fun (*this, &Route::set_plugin_state_dir), ""));
2695         }
2696
2697         return *node;
2698 }
2699
2700 int
2701 Route::set_state (const XMLNode& node, int version)
2702 {
2703         if (version < 3000) {
2704                 return set_state_2X (node, version);
2705         }
2706
2707         XMLNodeList nlist;
2708         XMLNodeConstIterator niter;
2709         XMLNode *child;
2710         const XMLProperty *prop;
2711
2712         if (node.name() != "Route"){
2713                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
2714                 return -1;
2715         }
2716
2717         if ((prop = node.property (X_("name"))) != 0) {
2718                 Route::set_name (prop->value());
2719         }
2720
2721         set_id (node);
2722         _initial_io_setup = true;
2723
2724         if ((prop = node.property (X_("flags"))) != 0) {
2725                 _flags = Flag (string_2_enum (prop->value(), _flags));
2726         } else {
2727                 _flags = Flag (0);
2728         }
2729
2730         if ((prop = node.property (X_("strict-io"))) != 0) {
2731                 _strict_io = string_is_affirmative (prop->value());
2732         }
2733
2734         if (is_master() || is_monitor() || is_auditioner()) {
2735                 _mute_master->set_solo_ignore (true);
2736         }
2737
2738         if (is_monitor()) {
2739                 /* monitor bus does not get a panner, but if (re)created
2740                    via XML, it will already have one by the time we
2741                    call ::set_state(). so ... remove it.
2742                 */
2743                 unpan ();
2744         }
2745
2746         /* add all processors (except amp, which is always present) */
2747
2748         nlist = node.children();
2749         XMLNode processor_state (X_("processor_state"));
2750
2751         Stateful::save_extra_xml (node);
2752
2753         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2754
2755                 child = *niter;
2756
2757                 if (child->name() == IO::state_node_name) {
2758                         if ((prop = child->property (X_("direction"))) == 0) {
2759                                 continue;
2760                         }
2761
2762                         if (prop->value() == "Input") {
2763                                 _input->set_state (*child, version);
2764                         } else if (prop->value() == "Output") {
2765                                 _output->set_state (*child, version);
2766                         }
2767                 }
2768
2769                 if (child->name() == X_("Processor")) {
2770                         processor_state.add_child_copy (*child);
2771                 }
2772
2773                 if (child->name() == X_("Pannable")) {
2774                         if (_pannable) {
2775                                 _pannable->set_state (*child, version);
2776                         } else {
2777                                 warning << string_compose (_("Pannable state found for route (%1) without a panner!"), name()) << endmsg;
2778                         }
2779                 }
2780         }
2781
2782         if ((prop = node.property (X_("meter-point"))) != 0) {
2783                 MeterPoint mp = MeterPoint (string_2_enum (prop->value (), _meter_point));
2784                 set_meter_point (mp, true);
2785                 if (_meter) {
2786                         _meter->set_display_to_user (_meter_point == MeterCustom);
2787                 }
2788         }
2789
2790         if ((prop = node.property (X_("meter-type"))) != 0) {
2791                 _meter_type = MeterType (string_2_enum (prop->value (), _meter_type));
2792         }
2793
2794         _initial_io_setup = false;
2795
2796         set_processor_state (processor_state);
2797
2798         // this looks up the internal instrument in processors
2799         reset_instrument_info();
2800
2801         if ((prop = node.property ("self-solo")) != 0) {
2802                 set_self_solo (string_is_affirmative (prop->value()));
2803         }
2804
2805         if ((prop = node.property ("soloed-by-upstream")) != 0) {
2806                 _soloed_by_others_upstream = 0; // needed for mod_.... () to work
2807                 mod_solo_by_others_upstream (atoi (prop->value()));
2808         }
2809
2810         if ((prop = node.property ("soloed-by-downstream")) != 0) {
2811                 _soloed_by_others_downstream = 0; // needed for mod_.... () to work
2812                 mod_solo_by_others_downstream (atoi (prop->value()));
2813         }
2814
2815         if ((prop = node.property ("solo-isolated")) != 0) {
2816                 set_solo_isolated (string_is_affirmative (prop->value()), Controllable::NoGroup);
2817         }
2818
2819         if ((prop = node.property ("solo-safe")) != 0) {
2820                 set_solo_safe (string_is_affirmative (prop->value()), Controllable::NoGroup);
2821         }
2822
2823         if ((prop = node.property (X_("phase-invert"))) != 0) {
2824                 set_phase_invert (boost::dynamic_bitset<> (prop->value ()));
2825         }
2826
2827         if ((prop = node.property (X_("denormal-protection"))) != 0) {
2828                 set_denormal_protection (string_is_affirmative (prop->value()));
2829         }
2830
2831         if ((prop = node.property (X_("active"))) != 0) {
2832                 bool yn = string_is_affirmative (prop->value());
2833                 _active = !yn; // force switch
2834                 set_active (yn, this);
2835         }
2836
2837         if ((prop = node.property (X_("order-key"))) != 0) { // New order key (no separate mixer/editor ordering)
2838                 set_order_key (atoi(prop->value()));
2839         }
2840
2841         if ((prop = node.property (X_("order-keys"))) != 0) { // Deprecated order keys
2842
2843                 int32_t n;
2844
2845                 string::size_type colon, equal;
2846                 string remaining = prop->value();
2847
2848                 while (remaining.length()) {
2849
2850                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
2851                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2852                                       << endmsg;
2853                         } else {
2854                                 if (sscanf (remaining.substr (equal+1).c_str(), "%d", &n) != 1) {
2855                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2856                                               << endmsg;
2857                                 } else {
2858                                         string keyname = remaining.substr (0, equal);
2859
2860                                         if ((keyname == "EditorSort") || (keyname == "editor")) {
2861                                                 cerr << "Setting " << name() << " order key to " << n << " using saved Editor order." << endl;
2862                                                 set_order_key (n);
2863                                         }
2864                                 }
2865                         }
2866
2867                         colon = remaining.find_first_of (':');
2868
2869                         if (colon != string::npos) {
2870                                 remaining = remaining.substr (colon+1);
2871                         } else {
2872                                 break;
2873                         }
2874                 }
2875         }
2876
2877         if ((prop = node.property (X_("processor-after-last-custom-meter"))) != 0) {
2878                 PBD::ID id (prop->value ());
2879                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
2880                 ProcessorList::const_iterator i = _processors.begin ();
2881                 while (i != _processors.end() && (*i)->id() != id) {
2882                         ++i;
2883                 }
2884
2885                 if (i != _processors.end ()) {
2886                         _processor_after_last_custom_meter = *i;
2887                         _custom_meter_position_noted = true;
2888                 }
2889         }
2890
2891         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2892                 child = *niter;
2893
2894                 if (child->name() == X_("Comment")) {
2895
2896                         /* XXX this is a terrible API design in libxml++ */
2897
2898                         XMLNode *cmt = *(child->children().begin());
2899                         _comment = cmt->content();
2900
2901                 } else if (child->name() == Controllable::xml_node_name && (prop = child->property("name")) != 0) {
2902                         if (prop->value() == "solo") {
2903                                 _solo_control->set_state (*child, version);
2904                         } else if (prop->value() == "mute") {
2905                                 _mute_control->set_state (*child, version);
2906                         }
2907
2908                 } else if (child->name() == X_("RemoteControl")) {
2909                         if ((prop = child->property (X_("id"))) != 0) {
2910                                 int32_t x;
2911                                 sscanf (prop->value().c_str(), "%d", &x);
2912                                 set_remote_control_id_internal (x);
2913                         }
2914
2915                 } else if (child->name() == X_("MuteMaster")) {
2916                         _mute_master->set_state (*child, version);
2917
2918                 } else if (child->name() == Automatable::xml_node_name) {
2919                         set_automation_xml_state (*child, Evoral::Parameter(NullAutomation));
2920                 }
2921         }
2922
2923         return 0;
2924 }
2925
2926 int
2927 Route::set_state_2X (const XMLNode& node, int version)
2928 {
2929         LocaleGuard lg (X_("C"));
2930         XMLNodeList nlist;
2931         XMLNodeConstIterator niter;
2932         XMLNode *child;
2933         const XMLProperty *prop;
2934
2935         /* 2X things which still remain to be handled:
2936          * default-type
2937          * automation
2938          * controlouts
2939          */
2940
2941         if (node.name() != "Route") {
2942                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
2943                 return -1;
2944         }
2945
2946         if ((prop = node.property (X_("flags"))) != 0) {
2947                 string f = prop->value ();
2948                 boost::replace_all (f, "ControlOut", "MonitorOut");
2949                 _flags = Flag (string_2_enum (f, _flags));
2950         } else {
2951                 _flags = Flag (0);
2952         }
2953
2954         if (is_master() || is_monitor() || is_auditioner()) {
2955                 _mute_master->set_solo_ignore (true);
2956         }
2957
2958         if ((prop = node.property (X_("phase-invert"))) != 0) {
2959                 boost::dynamic_bitset<> p (_input->n_ports().n_audio ());
2960                 if (string_is_affirmative (prop->value ())) {
2961                         p.set ();
2962                 }
2963                 set_phase_invert (p);
2964         }
2965
2966         if ((prop = node.property (X_("denormal-protection"))) != 0) {
2967                 set_denormal_protection (string_is_affirmative (prop->value()));
2968         }
2969
2970         if ((prop = node.property (X_("soloed"))) != 0) {
2971                 bool yn = string_is_affirmative (prop->value());
2972
2973                 /* XXX force reset of solo status */
2974
2975                 set_solo (yn);
2976         }
2977
2978         if ((prop = node.property (X_("muted"))) != 0) {
2979
2980                 bool first = true;
2981                 bool muted = string_is_affirmative (prop->value());
2982
2983                 if (muted) {
2984
2985                         string mute_point;
2986
2987                         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
2988
2989                                 if (string_is_affirmative (prop->value())){
2990                                         mute_point = mute_point + "PreFader";
2991                                         first = false;
2992                                 }
2993                         }
2994
2995                         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
2996
2997                                 if (string_is_affirmative (prop->value())){
2998
2999                                         if (!first) {
3000                                                 mute_point = mute_point + ",";
3001                                         }
3002
3003                                         mute_point = mute_point + "PostFader";
3004                                         first = false;
3005                                 }
3006                         }
3007
3008                         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
3009
3010                                 if (string_is_affirmative (prop->value())){
3011
3012                                         if (!first) {
3013                                                 mute_point = mute_point + ",";
3014                                         }
3015
3016                                         mute_point = mute_point + "Listen";
3017                                         first = false;
3018                                 }
3019                         }
3020
3021                         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
3022
3023                                 if (string_is_affirmative (prop->value())){
3024
3025                                         if (!first) {
3026                                                 mute_point = mute_point + ",";
3027                                         }
3028
3029                                         mute_point = mute_point + "Main";
3030                                 }
3031                         }
3032
3033                         _mute_master->set_mute_points (mute_point);
3034                         _mute_master->set_muted_by_self (true);
3035                 }
3036         }
3037
3038         if ((prop = node.property (X_("meter-point"))) != 0) {
3039                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
3040         }
3041
3042         /* do not carry over edit/mix groups from 2.X because (a) its hard (b) they
3043            don't mean the same thing.
3044         */
3045
3046         if ((prop = node.property (X_("order-keys"))) != 0) {
3047
3048                 int32_t n;
3049
3050                 string::size_type colon, equal;
3051                 string remaining = prop->value();
3052
3053                 while (remaining.length()) {
3054
3055                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
3056                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
3057                                         << endmsg;
3058                         } else {
3059                                 if (sscanf (remaining.substr (equal+1).c_str(), "%d", &n) != 1) {
3060                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
3061                                                 << endmsg;
3062                                 } else {
3063                                         string keyname = remaining.substr (0, equal);
3064
3065                                         if (keyname == "EditorSort" || keyname == "editor") {
3066                                                 info << string_compose(_("Converting deprecated order key for %1 using Editor order %2"), name (), n) << endmsg;
3067                                                 set_order_key (n);
3068                                         }
3069                                 }
3070                         }
3071
3072                         colon = remaining.find_first_of (':');
3073
3074                         if (colon != string::npos) {
3075                                 remaining = remaining.substr (colon+1);
3076                         } else {
3077                                 break;
3078                         }
3079                 }
3080         }
3081
3082         /* IOs */
3083
3084         nlist = node.children ();
3085         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
3086
3087                 child = *niter;
3088
3089                 if (child->name() == IO::state_node_name) {
3090
3091                         /* there is a note in IO::set_state_2X() about why we have to call
3092                            this directly.
3093                            */
3094
3095                         _input->set_state_2X (*child, version, true);
3096                         _output->set_state_2X (*child, version, false);
3097
3098                         if ((prop = child->property (X_("name"))) != 0) {
3099                                 Route::set_name (prop->value ());
3100                         }
3101
3102                         set_id (*child);
3103
3104                         if ((prop = child->property (X_("active"))) != 0) {
3105                                 bool yn = string_is_affirmative (prop->value());
3106                                 _active = !yn; // force switch
3107                                 set_active (yn, this);
3108                         }
3109
3110                         if ((prop = child->property (X_("gain"))) != 0) {
3111                                 gain_t val;
3112
3113                                 if (sscanf (prop->value().c_str(), "%f", &val) == 1) {
3114                                         _amp->gain_control()->set_value (val, Controllable::NoGroup);
3115                                 }
3116                         }
3117
3118                         /* Set up Panners in the IO */
3119                         XMLNodeList io_nlist = child->children ();
3120
3121                         XMLNodeConstIterator io_niter;
3122                         XMLNode *io_child;
3123
3124                         for (io_niter = io_nlist.begin(); io_niter != io_nlist.end(); ++io_niter) {
3125
3126                                 io_child = *io_niter;
3127
3128                                 if (io_child->name() == X_("Panner")) {
3129                                         _main_outs->panner_shell()->set_state(*io_child, version);
3130                                 } else if (io_child->name() == X_("Automation")) {
3131                                         /* IO's automation is for the fader */
3132                                         _amp->set_automation_xml_state (*io_child, Evoral::Parameter (GainAutomation));
3133                                 }
3134                         }
3135                 }
3136         }
3137
3138         XMLNodeList redirect_nodes;
3139
3140         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
3141
3142                 child = *niter;
3143
3144                 if (child->name() == X_("Send") || child->name() == X_("Insert")) {
3145                         redirect_nodes.push_back(child);
3146                 }
3147
3148         }
3149
3150         set_processor_state_2X (redirect_nodes, version);
3151
3152         Stateful::save_extra_xml (node);
3153
3154         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
3155                 child = *niter;
3156
3157                 if (child->name() == X_("Comment")) {
3158
3159                         /* XXX this is a terrible API design in libxml++ */
3160
3161                         XMLNode *cmt = *(child->children().begin());
3162                         _comment = cmt->content();
3163
3164                 } else if (child->name() == Controllable::xml_node_name && (prop = child->property("name")) != 0) {
3165                         if (prop->value() == X_("solo")) {
3166                                 _solo_control->set_state (*child, version);
3167                         } else if (prop->value() == X_("mute")) {
3168                                 _mute_control->set_state (*child, version);
3169                         }
3170
3171                 } else if (child->name() == X_("RemoteControl")) {
3172                         if ((prop = child->property (X_("id"))) != 0) {
3173                                 int32_t x;
3174                                 sscanf (prop->value().c_str(), "%d", &x);
3175                                 set_remote_control_id_internal (x);
3176                         }
3177
3178                 }
3179         }
3180
3181         return 0;
3182 }
3183
3184 XMLNode&
3185 Route::get_processor_state ()
3186 {
3187         XMLNode* root = new XMLNode (X_("redirects"));
3188         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3189                 root->add_child_nocopy ((*i)->state (true));
3190         }
3191
3192         return *root;
3193 }
3194
3195 void
3196 Route::set_processor_state_2X (XMLNodeList const & nList, int version)
3197 {
3198         /* We don't bother removing existing processors not in nList, as this
3199            method will only be called when creating a Route from scratch, not
3200            for undo purposes.  Just put processors in at the appropriate place
3201            in the list.
3202         */
3203
3204         for (XMLNodeConstIterator i = nList.begin(); i != nList.end(); ++i) {
3205                 add_processor_from_xml_2X (**i, version);
3206         }
3207 }
3208
3209 void
3210 Route::set_processor_state (const XMLNode& node)
3211 {
3212         const XMLNodeList &nlist = node.children();
3213         XMLNodeConstIterator niter;
3214         ProcessorList new_order;
3215         bool must_configure = false;
3216
3217         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
3218
3219                 XMLProperty* prop = (*niter)->property ("type");
3220
3221                 if (prop->value() == "amp") {
3222                         _amp->set_state (**niter, Stateful::current_state_version);
3223                         new_order.push_back (_amp);
3224                 } else if (prop->value() == "trim") {
3225                         _trim->set_state (**niter, Stateful::current_state_version);
3226                         new_order.push_back (_trim);
3227                 } else if (prop->value() == "meter") {
3228                         _meter->set_state (**niter, Stateful::current_state_version);
3229                         new_order.push_back (_meter);
3230                 } else if (prop->value() == "delay") {
3231                         if (_delayline) {
3232                                 _delayline->set_state (**niter, Stateful::current_state_version);
3233                                 new_order.push_back (_delayline);
3234                         }
3235                 } else if (prop->value() == "main-outs") {
3236                         _main_outs->set_state (**niter, Stateful::current_state_version);
3237                 } else if (prop->value() == "intreturn") {
3238                         if (!_intreturn) {
3239                                 _intreturn.reset (new InternalReturn (_session));
3240                                 must_configure = true;
3241                         }
3242                         _intreturn->set_state (**niter, Stateful::current_state_version);
3243                 } else if (is_monitor() && prop->value() == "monitor") {
3244                         if (!_monitor_control) {
3245                                 _monitor_control.reset (new MonitorProcessor (_session));
3246                                 must_configure = true;
3247                         }
3248                         _monitor_control->set_state (**niter, Stateful::current_state_version);
3249                 } else if (prop->value() == "capture") {
3250                         /* CapturingProcessor should never be restored, it's always
3251                            added explicitly when needed */
3252                 } else {
3253                         ProcessorList::iterator o;
3254
3255                         for (o = _processors.begin(); o != _processors.end(); ++o) {
3256                                 XMLProperty* id_prop = (*niter)->property(X_("id"));
3257                                 if (id_prop && (*o)->id() == id_prop->value()) {
3258                                         (*o)->set_state (**niter, Stateful::current_state_version);
3259                                         new_order.push_back (*o);
3260                                         break;
3261                                 }
3262                         }
3263
3264                         // If the processor (*niter) is not on the route then create it
3265
3266                         if (o == _processors.end()) {
3267
3268                                 boost::shared_ptr<Processor> processor;
3269
3270                                 if (prop->value() == "intsend") {
3271
3272                                         processor.reset (new InternalSend (_session, _pannable, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), boost::shared_ptr<Route>(), Delivery::Aux, true));
3273
3274                                 } else if (prop->value() == "ladspa" || prop->value() == "Ladspa" ||
3275                                            prop->value() == "lv2" ||
3276                                            prop->value() == "windows-vst" ||
3277                                            prop->value() == "lxvst" ||
3278                                            prop->value() == "luaproc" ||
3279                                            prop->value() == "audiounit") {
3280
3281                                         if (_session.get_disable_all_loaded_plugins ()) {
3282                                                 processor.reset (new UnknownProcessor (_session, **niter));
3283                                         } else {
3284                                                 processor.reset (new PluginInsert (_session));
3285                                                 processor->set_owner (this);
3286                                                 if (_strict_io) {
3287                                                         boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(processor);
3288                                                         pi->set_strict_io (true);
3289                                                 }
3290
3291                                         }
3292                                 } else if (prop->value() == "port") {
3293
3294                                         processor.reset (new PortInsert (_session, _pannable, _mute_master));
3295
3296                                 } else if (prop->value() == "send") {
3297
3298                                         processor.reset (new Send (_session, _pannable, _mute_master, Delivery::Send, true));
3299
3300                                 } else {
3301                                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
3302                                         continue;
3303                                 }
3304
3305                                 if (processor->set_state (**niter, Stateful::current_state_version) != 0) {
3306                                         /* This processor could not be configured.  Turn it into a UnknownProcessor */
3307                                         processor.reset (new UnknownProcessor (_session, **niter));
3308                                 }
3309
3310                                 /* subscribe to Sidechain IO changes */
3311                                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert> (processor);
3312                                 if (pi && pi->has_sidechain ()) {
3313                                         pi->sidechain_input ()->changed.connect_same_thread (*this, boost::bind (&Route::sidechain_change_handler, this, _1, _2));
3314                                 }
3315
3316                                 /* we have to note the monitor send here, otherwise a new one will be created
3317                                    and the state of this one will be lost.
3318                                 */
3319                                 boost::shared_ptr<InternalSend> isend = boost::dynamic_pointer_cast<InternalSend> (processor);
3320                                 if (isend && isend->role() == Delivery::Listen) {
3321                                         _monitor_send = isend;
3322                                 }
3323
3324                                 /* it doesn't matter if invisible processors are added here, as they
3325                                    will be sorted out by setup_invisible_processors () shortly.
3326                                 */
3327
3328                                 new_order.push_back (processor);
3329                                 must_configure = true;
3330                         }
3331                 }
3332         }
3333
3334         {
3335                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
3336                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
3337                 _processors = new_order;
3338
3339                 if (must_configure) {
3340                         configure_processors_unlocked (0);
3341                 }
3342
3343                 for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3344
3345                         (*i)->set_owner (this);
3346                         (*i)->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false));
3347
3348                         boost::shared_ptr<PluginInsert> pi;
3349
3350                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
3351                                 if (pi->has_no_inputs ()) {
3352                                         _have_internal_generator = true;
3353                                         break;
3354                                 }
3355                         }
3356                 }
3357         }
3358
3359         reset_instrument_info ();
3360         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
3361         set_processor_positions ();
3362 }
3363
3364 void
3365 Route::curve_reallocate ()
3366 {
3367 //      _gain_automation_curve.finish_resize ();
3368 //      _pan_automation_curve.finish_resize ();
3369 }
3370
3371 void
3372 Route::silence (framecnt_t nframes)
3373 {
3374         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
3375         if (!lm.locked()) {
3376                 return;
3377         }
3378
3379         silence_unlocked (nframes);
3380 }
3381
3382 void
3383 Route::silence_unlocked (framecnt_t nframes)
3384 {
3385         /* Must be called with the processor lock held */
3386
3387         if (!_silent) {
3388
3389                 _output->silence (nframes);
3390
3391                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3392                         boost::shared_ptr<PluginInsert> pi;
3393
3394                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
3395                                 // skip plugins, they don't need anything when we're not active
3396                                 continue;
3397                         }
3398
3399                         (*i)->silence (nframes);
3400                 }
3401
3402                 if (nframes == _session.get_block_size()) {
3403                         // _silent = true;
3404                 }
3405         }
3406 }
3407
3408 void
3409 Route::add_internal_return ()
3410 {
3411         if (!_intreturn) {
3412                 _intreturn.reset (new InternalReturn (_session));
3413                 add_processor (_intreturn, PreFader);
3414         }
3415 }
3416
3417 void
3418 Route::add_send_to_internal_return (InternalSend* send)
3419 {
3420         Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3421
3422         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
3423                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
3424
3425                 if (d) {
3426                         return d->add_send (send);
3427                 }
3428         }
3429 }
3430
3431 void
3432 Route::remove_send_from_internal_return (InternalSend* send)
3433 {
3434         Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3435
3436         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
3437                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
3438
3439                 if (d) {
3440                         return d->remove_send (send);
3441                 }
3442         }
3443 }
3444
3445 void
3446 Route::enable_monitor_send ()
3447 {
3448         /* Caller must hold process lock */
3449         assert (!AudioEngine::instance()->process_lock().trylock());
3450
3451         /* master never sends to monitor section via the normal mechanism */
3452         assert (!is_master ());
3453         assert (!is_monitor ());
3454
3455         /* make sure we have one */
3456         if (!_monitor_send) {
3457                 _monitor_send.reset (new InternalSend (_session, _pannable, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), _session.monitor_out(), Delivery::Listen));
3458                 _monitor_send->set_display_to_user (false);
3459         }
3460
3461         /* set it up */
3462         configure_processors (0);
3463 }
3464
3465 /** Add an aux send to a route.
3466  *  @param route route to send to.
3467  *  @param before Processor to insert before, or 0 to insert at the end.
3468  */
3469 int
3470 Route::add_aux_send (boost::shared_ptr<Route> route, boost::shared_ptr<Processor> before)
3471 {
3472         assert (route != _session.monitor_out ());
3473
3474         {
3475                 Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
3476
3477                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
3478
3479                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend> (*x);
3480
3481                         if (d && d->target_route() == route) {
3482                                 /* already listening via the specified IO: do nothing */
3483                                 return 0;
3484                         }
3485                 }
3486         }
3487
3488         try {
3489
3490                 boost::shared_ptr<InternalSend> listener;
3491
3492                 {
3493                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
3494                         boost::shared_ptr<Pannable> sendpan (new Pannable (_session));
3495                         listener.reset (new InternalSend (_session, sendpan, _mute_master, boost::dynamic_pointer_cast<ARDOUR::Route>(shared_from_this()), route, Delivery::Aux));
3496                 }
3497
3498                 add_processor (listener, before);
3499
3500         } catch (failed_constructor& err) {
3501                 return -1;
3502         }
3503
3504         return 0;
3505 }
3506
3507 void
3508 Route::remove_aux_or_listen (boost::shared_ptr<Route> route)
3509 {
3510         ProcessorStreams err;
3511         ProcessorList::iterator tmp;
3512
3513         {
3514                 Glib::Threads::RWLock::ReaderLock rl(_processor_lock);
3515
3516                 /* have to do this early because otherwise processor reconfig
3517                  * will put _monitor_send back in the list
3518                  */
3519
3520                 if (route == _session.monitor_out()) {
3521                         _monitor_send.reset ();
3522                 }
3523
3524           again:
3525                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
3526
3527                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
3528
3529                         if (d && d->target_route() == route) {
3530                                 rl.release ();
3531                                 if (remove_processor (*x, &err, false) > 0) {
3532                                         rl.acquire ();
3533                                         continue;
3534                                 }
3535                                 rl.acquire ();
3536
3537                                 /* list could have been demolished while we dropped the lock
3538                                    so start over.
3539                                 */
3540                                 if (_session.engine().connected()) {
3541                                         /* i/o processors cannot be removed if the engine is not running
3542                                          * so don't live-loop in case the engine is N/A or dies
3543                                          */
3544                                         goto again;
3545                                 }
3546                         }
3547                 }
3548         }
3549 }
3550
3551 void
3552 Route::set_comment (string cmt, void *src)
3553 {
3554         _comment = cmt;
3555         comment_changed ();
3556         _session.set_dirty ();
3557 }
3558
3559 bool
3560 Route::add_fed_by (boost::shared_ptr<Route> other, bool via_sends_only)
3561 {
3562         FeedRecord fr (other, via_sends_only);
3563
3564         pair<FedBy::iterator,bool> result =  _fed_by.insert (fr);
3565
3566         if (!result.second) {
3567
3568                 /* already a record for "other" - make sure sends-only information is correct */
3569                 if (!via_sends_only && result.first->sends_only) {
3570                         FeedRecord* frp = const_cast<FeedRecord*>(&(*result.first));
3571                         frp->sends_only = false;
3572                 }
3573         }
3574
3575         return result.second;
3576 }
3577
3578 void
3579 Route::clear_fed_by ()
3580 {
3581         _fed_by.clear ();
3582 }
3583
3584 bool
3585 Route::feeds (boost::shared_ptr<Route> other, bool* via_sends_only)
3586 {
3587         const FedBy& fed_by (other->fed_by());
3588
3589         for (FedBy::const_iterator f = fed_by.begin(); f != fed_by.end(); ++f) {
3590                 boost::shared_ptr<Route> sr = f->r.lock();
3591
3592                 if (sr && (sr.get() == this)) {
3593
3594                         if (via_sends_only) {
3595                                 *via_sends_only = f->sends_only;
3596                         }
3597
3598                         return true;
3599                 }
3600         }
3601
3602         return false;
3603 }
3604
3605 IOVector
3606 Route::all_inputs () const
3607 {
3608         /* TODO, if this works as expected,
3609          * cache the IOVector and maintain it via
3610          * input_change_handler(), sidechain_change_handler() etc
3611          */
3612         IOVector ios;
3613         ios.push_back (_input);
3614
3615         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3616         for (ProcessorList::const_iterator r = _processors.begin(); r != _processors.end(); ++r) {
3617
3618                 boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*r);
3619                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*r);
3620                 if (pi != 0) {
3621                         assert (iop == 0);
3622                         iop = pi->sidechain();
3623                 }
3624
3625                 if (iop != 0 && iop->input()) {
3626                         ios.push_back (iop->input());
3627                 }
3628         }
3629         return ios;
3630 }
3631
3632 IOVector
3633 Route::all_outputs () const
3634 {
3635         IOVector ios;
3636         // _output is included via Delivery
3637         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3638         for (ProcessorList::const_iterator r = _processors.begin(); r != _processors.end(); ++r) {
3639                 boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*r);
3640                 if (iop != 0 && iop->output()) {
3641                         ios.push_back (iop->output());
3642                 }
3643         }
3644         return ios;
3645 }
3646
3647 bool
3648 Route::direct_feeds_according_to_reality (boost::shared_ptr<Route> other, bool* via_send_only)
3649 {
3650         DEBUG_TRACE (DEBUG::Graph, string_compose ("Feeds? %1\n", _name));
3651         if (other->all_inputs().fed_by (_output)) {
3652                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\tdirect FEEDS %2\n", other->name()));
3653                 if (via_send_only) {
3654                         *via_send_only = false;
3655                 }
3656
3657                 return true;
3658         }
3659
3660
3661         Glib::Threads::RWLock::ReaderLock lm (_processor_lock); // XXX
3662         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); ++r) {
3663
3664                 boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor>(*r);
3665                 boost::shared_ptr<PluginInsert> pi = boost::dynamic_pointer_cast<PluginInsert>(*r);
3666                 if (pi != 0) {
3667                         assert (iop == 0);
3668                         iop = pi->sidechain();
3669                 }
3670
3671                 if (iop != 0) {
3672                         boost::shared_ptr<const IO> iop_out = iop->output();
3673                         if ((iop_out && other->all_inputs().fed_by (iop_out)) || iop->feeds (other)) {
3674                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does feed %2\n", iop->name(), other->name()));
3675                                 if (via_send_only) {
3676                                         *via_send_only = true;
3677                                 }
3678                                 return true;
3679                         } else {
3680                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does NOT feed %2\n", iop->name(), other->name()));
3681                         }
3682                 } else {
3683                         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tPROC %1 is not an IOP\n", (*r)->name()));
3684                 }
3685
3686         }
3687
3688         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tdoes NOT feed %1\n", other->name()));
3689         return false;
3690 }
3691
3692 bool
3693 Route::direct_feeds_according_to_graph (boost::shared_ptr<Route> other, bool* via_send_only)
3694 {
3695         return _session._current_route_graph.has (shared_from_this (), other, via_send_only);
3696 }
3697
3698 bool
3699 Route::feeds_according_to_graph (boost::shared_ptr<Route> other)
3700 {
3701         return _session._current_route_graph.feeds (shared_from_this (), other);
3702 }
3703
3704 /** Called from the (non-realtime) butler thread when the transport is stopped */
3705 void
3706 Route::nonrealtime_handle_transport_stopped (bool /*abort_ignored*/, bool /*did_locate*/, bool can_flush_processors)
3707 {
3708         framepos_t now = _session.transport_frame();
3709
3710         {
3711                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3712
3713                 Automatable::transport_stopped (now);
3714
3715                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3716
3717                         if (!_have_internal_generator && (Config->get_plugins_stop_with_transport() && can_flush_processors)) {
3718                                 (*i)->flush ();
3719                         }
3720
3721                         (*i)->transport_stopped (now);
3722                 }
3723         }
3724
3725         _roll_delay = _initial_delay;
3726 }
3727
3728 void
3729 Route::input_change_handler (IOChange change, void * /*src*/)
3730 {
3731         if ((change.type & IOChange::ConfigurationChanged)) {
3732                 /* This is called with the process lock held if change
3733                    contains ConfigurationChanged
3734                 */
3735                 configure_processors (0);
3736                 _phase_invert.resize (_input->n_ports().n_audio ());
3737                 io_changed (); /* EMIT SIGNAL */
3738         }
3739
3740         if (_soloed_by_others_upstream || _solo_isolated_by_upstream) {
3741                 int sbou = 0;
3742                 int ibou = 0;
3743                 boost::shared_ptr<RouteList> routes = _session.get_routes ();
3744                 if (_input->connected()) {
3745                         for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3746                                 if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3747                                         continue;
3748                                 }
3749                                 bool sends_only;
3750                                 bool does_feed = (*i)->direct_feeds_according_to_reality (shared_from_this(), &sends_only);
3751                                 if (does_feed && !sends_only) {
3752                                         if ((*i)->soloed()) {
3753                                                 ++sbou;
3754                                         }
3755                                         if ((*i)->solo_isolated()) {
3756                                                 ++ibou;
3757                                         }
3758                                 }
3759                         }
3760                 }
3761
3762                 int delta  = sbou - _soloed_by_others_upstream;
3763                 int idelta = ibou - _solo_isolated_by_upstream;
3764
3765                 if (idelta < -1) {
3766                         PBD::warning << string_compose (
3767                                         _("Invalid Solo-Isolate propagation: from:%1 new:%2 - old:%3 = delta:%4"),
3768                                         _name, ibou, _solo_isolated_by_upstream, idelta)
3769                                      << endmsg;
3770
3771                 }
3772
3773                 if (_soloed_by_others_upstream) {
3774                         // ignore new connections (they're not propagated)
3775                         if (delta <= 0) {
3776                                 mod_solo_by_others_upstream (delta);
3777                         }
3778                 }
3779
3780                 if (_solo_isolated_by_upstream) {
3781                         // solo-isolate currently only propagates downstream
3782                         if (idelta < 0) {
3783                                 mod_solo_isolated_by_upstream (false);
3784                         }
3785                         // TODO think: mod_solo_isolated_by_upstream() does not take delta arg,
3786                         // but idelta can't be smaller than -1, can it?
3787                         //_solo_isolated_by_upstream = ibou;
3788                 }
3789
3790                 // Session::route_solo_changed  does not propagate indirect solo-changes
3791                 // propagate downstream to tracks
3792                 for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3793                         if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3794                                 continue;
3795                         }
3796                         bool sends_only;
3797                         bool does_feed = feeds (*i, &sends_only);
3798                         if (delta <= 0 && does_feed && !sends_only) {
3799                                 (*i)->mod_solo_by_others_upstream (delta);
3800                         }
3801
3802                         if (idelta < 0 && does_feed && !sends_only) {
3803                                 (*i)->mod_solo_isolated_by_upstream (false);
3804                         }
3805                 }
3806         }
3807 }
3808
3809 void
3810 Route::output_change_handler (IOChange change, void * /*src*/)
3811 {
3812         if (_initial_io_setup) {
3813                 return;
3814         }
3815
3816         if ((change.type & IOChange::ConfigurationChanged)) {
3817                 /* This is called with the process lock held if change
3818                    contains ConfigurationChanged
3819                 */
3820                 configure_processors (0);
3821
3822                 if (is_master()) {
3823                         _session.reset_monitor_section();
3824                 }
3825
3826                 io_changed (); /* EMIT SIGNAL */
3827         }
3828
3829         if (_soloed_by_others_downstream) {
3830                 int sbod = 0;
3831                 /* checking all all downstream routes for
3832                  * explicit of implict solo is a rather drastic measure,
3833                  * ideally the input_change_handler() of the other route
3834                  * would propagate the change to us.
3835                  */
3836                 boost::shared_ptr<RouteList> routes = _session.get_routes ();
3837                 if (_output->connected()) {
3838                         for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3839                                 if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3840                                         continue;
3841                                 }
3842                                 bool sends_only;
3843                                 bool does_feed = direct_feeds_according_to_reality (*i, &sends_only);
3844                                 if (does_feed && !sends_only) {
3845                                         if ((*i)->soloed()) {
3846                                                 ++sbod;
3847                                                 break;
3848                                         }
3849                                 }
3850                         }
3851                 }
3852                 int delta = sbod - _soloed_by_others_downstream;
3853                 if (delta <= 0) {
3854                         // do not allow new connections to change implicit solo (no propagation)
3855                         mod_solo_by_others_downstream (delta);
3856                         // Session::route_solo_changed() does not propagate indirect solo-changes
3857                         // propagate upstream to tracks
3858                         for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
3859                                 if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
3860                                         continue;
3861                                 }
3862                                 bool sends_only;
3863                                 bool does_feed = (*i)->feeds (shared_from_this(), &sends_only);
3864                                 if (delta != 0 && does_feed && !sends_only) {
3865                                         (*i)->mod_solo_by_others_downstream (delta);
3866                                 }
3867                         }
3868
3869                 }
3870         }
3871 }
3872
3873 void
3874 Route::sidechain_change_handler (IOChange change, void * /*src*/)
3875 {
3876         if (_initial_io_setup || _in_sidechain_setup) {
3877                 return;
3878         }
3879
3880         if ((change.type & IOChange::ConfigurationChanged)) {
3881                 /* This is called with the process lock held if change
3882                    contains ConfigurationChanged
3883                 */
3884                 configure_processors (0);
3885         }
3886 }
3887
3888 uint32_t
3889 Route::pans_required () const
3890 {
3891         if (n_outputs().n_audio() < 2) {
3892                 return 0;
3893         }
3894
3895         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
3896 }
3897
3898 int
3899 Route::no_roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, bool session_state_changing)
3900 {
3901         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
3902
3903         if (!lm.locked()) {
3904                 return 0;
3905         }
3906
3907         if (n_outputs().n_total() == 0) {
3908                 return 0;
3909         }
3910
3911         if (!_active || n_inputs() == ChanCount::ZERO)  {
3912                 silence_unlocked (nframes);
3913                 return 0;
3914         }
3915
3916         if (session_state_changing) {
3917                 if (_session.transport_speed() != 0.0f) {
3918                         /* we're rolling but some state is changing (e.g. our diskstream contents)
3919                            so we cannot use them. Be silent till this is over.
3920
3921                            XXX note the absurdity of ::no_roll() being called when we ARE rolling!
3922                         */
3923                         silence_unlocked (nframes);
3924                         return 0;
3925                 }
3926                 /* we're really not rolling, so we're either delivery silence or actually
3927                    monitoring, both of which are safe to do while session_state_changing is true.
3928                 */
3929         }
3930
3931         BufferSet& bufs = _session.get_route_buffers (n_process_buffers());
3932
3933         fill_buffers_with_input (bufs, _input, nframes);
3934
3935         if (_meter_point == MeterInput) {
3936                 _meter->run (bufs, start_frame, end_frame, nframes, true);
3937         }
3938
3939         _amp->apply_gain_automation (false);
3940         _trim->apply_gain_automation (false);
3941         passthru (bufs, start_frame, end_frame, nframes, 0);
3942
3943         return 0;
3944 }
3945
3946 int
3947 Route::roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& /* need_butler */)
3948 {
3949         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
3950         if (!lm.locked()) {
3951                 return 0;
3952         }
3953
3954         if (n_outputs().n_total() == 0) {
3955                 return 0;
3956         }
3957
3958         if (!_active || n_inputs().n_total() == 0) {
3959                 silence_unlocked (nframes);
3960                 return 0;
3961         }
3962
3963         framepos_t unused = 0;
3964
3965         if ((nframes = check_initial_delay (nframes, unused)) == 0) {
3966                 return 0;
3967         }
3968
3969         _silent = false;
3970
3971         BufferSet& bufs = _session.get_route_buffers (n_process_buffers());
3972
3973         fill_buffers_with_input (bufs, _input, nframes);
3974
3975         if (_meter_point == MeterInput) {
3976                 _meter->run (bufs, start_frame, end_frame, nframes, true);
3977         }
3978
3979         passthru (bufs, start_frame, end_frame, nframes, declick);
3980
3981         return 0;
3982 }
3983
3984 int
3985 Route::silent_roll (pframes_t nframes, framepos_t /*start_frame*/, framepos_t /*end_frame*/, bool& /* need_butler */)
3986 {
3987         silence (nframes);
3988         return 0;
3989 }
3990
3991 void
3992 Route::flush_processors ()
3993 {
3994         /* XXX shouldn't really try to take this lock, since
3995            this is called from the RT audio thread.
3996         */
3997
3998         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
3999
4000         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4001                 (*i)->flush ();
4002         }
4003 }
4004
4005 #ifdef __clang__
4006 __attribute__((annotate("realtime")))
4007 #endif
4008 bool
4009 Route::apply_processor_changes_rt ()
4010 {
4011         int emissions = EmitNone;
4012
4013         if (_pending_meter_point != _meter_point) {
4014                 Glib::Threads::RWLock::WriterLock pwl (_processor_lock, Glib::Threads::TRY_LOCK);
4015                 if (pwl.locked()) {
4016                         /* meters always have buffers for 'processor_max_streams'
4017                          * they can be re-positioned without re-allocation */
4018                         if (set_meter_point_unlocked()) {
4019                                 emissions |= EmitMeterChanged | EmitMeterVisibilityChange;;
4020                         } else {
4021                                 emissions |= EmitMeterChanged;
4022                         }
4023                 }
4024         }
4025
4026         bool changed = false;
4027
4028         if (g_atomic_int_get (&_pending_process_reorder)) {
4029                 Glib::Threads::RWLock::WriterLock pwl (_processor_lock, Glib::Threads::TRY_LOCK);
4030                 if (pwl.locked()) {
4031                         apply_processor_order (_pending_processor_order);
4032                         setup_invisible_processors ();
4033                         changed = true;
4034                         g_atomic_int_set (&_pending_process_reorder, 0);
4035                         emissions |= EmitRtProcessorChange;
4036                 }
4037         }
4038         if (changed) {
4039                 set_processor_positions ();
4040         }
4041         if (emissions != 0) {
4042                 g_atomic_int_set (&_pending_signals, emissions);
4043                 return true;
4044         }
4045         return false;
4046 }
4047
4048 void
4049 Route::emit_pending_signals ()
4050 {
4051
4052         int sig = g_atomic_int_and (&_pending_signals, 0);
4053         if (sig & EmitMeterChanged) {
4054                 _meter->emit_configuration_changed();
4055                 meter_change (); /* EMIT SIGNAL */
4056                 if (sig & EmitMeterVisibilityChange) {
4057                 processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, true)); /* EMIT SIGNAL */
4058                 } else {
4059                 processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, false)); /* EMIT SIGNAL */
4060                 }
4061         }
4062         if (sig & EmitRtProcessorChange) {
4063                 processors_changed (RouteProcessorChange (RouteProcessorChange::RealTimeChange)); /* EMIT SIGNAL */
4064         }
4065 }
4066
4067 void
4068 Route::set_meter_point (MeterPoint p, bool force)
4069 {
4070         if (_pending_meter_point == p && !force) {
4071                 return;
4072         }
4073
4074         if (force || !AudioEngine::instance()->running()) {
4075                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
4076                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
4077                 _pending_meter_point = p;
4078                 _meter->emit_configuration_changed();
4079                 meter_change (); /* EMIT SIGNAL */
4080                 if (set_meter_point_unlocked()) {
4081                         processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, true)); /* EMIT SIGNAL */
4082                 } else {
4083                         processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, false)); /* EMIT SIGNAL */
4084                 }
4085         } else {
4086                 _pending_meter_point = p;
4087         }
4088 }
4089
4090
4091 #ifdef __clang__
4092 __attribute__((annotate("realtime")))
4093 #endif
4094 bool
4095 Route::set_meter_point_unlocked ()
4096 {
4097 #ifndef NDEBUG
4098         /* Caller must hold process and processor write lock */
4099         assert (!AudioEngine::instance()->process_lock().trylock());
4100         Glib::Threads::RWLock::WriterLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
4101         assert (!lm.locked ());
4102 #endif
4103
4104         _meter_point = _pending_meter_point;
4105
4106         bool meter_was_visible_to_user = _meter->display_to_user ();
4107
4108         if (!_custom_meter_position_noted) {
4109                 maybe_note_meter_position ();
4110         }
4111
4112         if (_meter_point != MeterCustom) {
4113
4114                 _meter->set_display_to_user (false);
4115
4116                 setup_invisible_processors ();
4117
4118         } else {
4119                 _meter->set_display_to_user (true);
4120
4121                 /* If we have a previous position for the custom meter, try to put it there */
4122                 boost::shared_ptr<Processor> after = _processor_after_last_custom_meter.lock ();
4123                 if (after) {
4124                         ProcessorList::iterator i = find (_processors.begin(), _processors.end(), after);
4125                         if (i != _processors.end ()) {
4126                                 _processors.remove (_meter);
4127                                 _processors.insert (i, _meter);
4128                         }
4129                 } else {// at end, right before the mains_out/panner
4130                         _processors.remove (_meter);
4131                         ProcessorList::iterator main = _processors.end();
4132                         _processors.insert (--main, _meter);
4133                 }
4134         }
4135
4136         /* Set up the meter for its new position */
4137
4138         ProcessorList::iterator loc = find (_processors.begin(), _processors.end(), _meter);
4139
4140         ChanCount m_in;
4141
4142         if (loc == _processors.begin()) {
4143                 m_in = _input->n_ports();
4144         } else {
4145                 ProcessorList::iterator before = loc;
4146                 --before;
4147                 m_in = (*before)->output_streams ();
4148         }
4149
4150         _meter->reflect_inputs (m_in);
4151
4152         /* we do not need to reconfigure the processors, because the meter
4153            (a) is always ready to handle processor_max_streams
4154            (b) is always an N-in/N-out processor, and thus moving
4155            it doesn't require any changes to the other processors.
4156         */
4157
4158         /* these should really be done after releasing the lock
4159          * but all those signals are subscribed to with gui_thread()
4160          * so we're safe.
4161          */
4162          return (_meter->display_to_user() != meter_was_visible_to_user);
4163 }
4164
4165 void
4166 Route::listen_position_changed ()
4167 {
4168         {
4169                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
4170                 Glib::Threads::RWLock::WriterLock lm (_processor_lock);
4171                 ProcessorState pstate (this);
4172
4173                 if (configure_processors_unlocked (0)) {
4174                         DEBUG_TRACE (DEBUG::Processors, "---- CONFIGURATION FAILED.\n");
4175                         pstate.restore ();
4176                         configure_processors_unlocked (0); // it worked before we tried to add it ...
4177                         return;
4178                 }
4179         }
4180
4181         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
4182         _session.set_dirty ();
4183 }
4184
4185 boost::shared_ptr<CapturingProcessor>
4186 Route::add_export_point()
4187 {
4188         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4189         if (!_capturing_processor) {
4190                 lm.release();
4191                 Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
4192                 Glib::Threads::RWLock::WriterLock lw (_processor_lock);
4193
4194                 _capturing_processor.reset (new CapturingProcessor (_session));
4195                 _capturing_processor->activate ();
4196
4197                 configure_processors_unlocked (0);
4198
4199         }
4200
4201         return _capturing_processor;
4202 }
4203
4204 framecnt_t
4205 Route::update_signal_latency ()
4206 {
4207         framecnt_t l = _output->user_latency();
4208         framecnt_t lamp = 0;
4209         bool before_amp = true;
4210         framecnt_t ltrim = 0;
4211         bool before_trim = true;
4212
4213         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4214                 if ((*i)->active ()) {
4215                         l += (*i)->signal_latency ();
4216                 }
4217                 if ((*i) == _amp) {
4218                         before_amp = false;
4219                 }
4220                 if ((*i) == _trim) {
4221                         before_amp = false;
4222                 }
4223                 if (before_amp) {
4224                         lamp = l;
4225                 }
4226                 if (before_trim) {
4227                         lamp = l;
4228                 }
4229         }
4230
4231         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: internal signal latency = %2\n", _name, l));
4232
4233         // TODO: (lamp - _signal_latency) to sync to output (read-ahed),  currently _roll_delay shifts this around
4234         _signal_latency_at_amp_position = lamp;
4235         _signal_latency_at_trim_position = ltrim;
4236
4237         if (_signal_latency != l) {
4238                 _signal_latency = l;
4239                 signal_latency_changed (); /* EMIT SIGNAL */
4240         }
4241
4242         return _signal_latency;
4243 }
4244
4245 void
4246 Route::set_user_latency (framecnt_t nframes)
4247 {
4248         _output->set_user_latency (nframes);
4249         _session.update_latency_compensation ();
4250 }
4251
4252 void
4253 Route::set_latency_compensation (framecnt_t longest_session_latency)
4254 {
4255         framecnt_t old = _initial_delay;
4256
4257         if (_signal_latency < longest_session_latency) {
4258                 _initial_delay = longest_session_latency - _signal_latency;
4259         } else {
4260                 _initial_delay = 0;
4261         }
4262
4263         DEBUG_TRACE (DEBUG::Latency, string_compose (
4264                              "%1: compensate for maximum latency of %2,"
4265                              "given own latency of %3, using initial delay of %4\n",
4266                              name(), longest_session_latency, _signal_latency, _initial_delay));
4267
4268         if (_initial_delay != old) {
4269                 initial_delay_changed (); /* EMIT SIGNAL */
4270         }
4271
4272         if (_session.transport_stopped()) {
4273                 _roll_delay = _initial_delay;
4274         }
4275 }
4276
4277 void
4278 Route::set_block_size (pframes_t nframes)
4279 {
4280         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4281                 (*i)->set_block_size (nframes);
4282         }
4283
4284         _session.ensure_buffers (n_process_buffers ());
4285 }
4286
4287 void
4288 Route::protect_automation ()
4289 {
4290         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
4291                 (*i)->protect_automation();
4292 }
4293
4294 /** @param declick 1 to set a pending declick fade-in,
4295  *                -1 to set a pending declick fade-out
4296  */
4297 void
4298 Route::set_pending_declick (int declick)
4299 {
4300         if (_declickable) {
4301                 /* this call is not allowed to turn off a pending declick */
4302                 if (declick) {
4303                         _pending_declick = declick;
4304                 }
4305         } else {
4306                 _pending_declick = 0;
4307         }
4308 }
4309
4310 /** Shift automation forwards from a particular place, thereby inserting time.
4311  *  Adds undo commands for any shifts that are performed.
4312  *
4313  * @param pos Position to start shifting from.
4314  * @param frames Amount to shift forwards by.
4315  */
4316
4317 void
4318 Route::shift (framepos_t pos, framecnt_t frames)
4319 {
4320         /* gain automation */
4321         {
4322                 boost::shared_ptr<AutomationControl> gc = _amp->gain_control();
4323
4324                 XMLNode &before = gc->alist()->get_state ();
4325                 gc->alist()->shift (pos, frames);
4326                 XMLNode &after = gc->alist()->get_state ();
4327                 _session.add_command (new MementoCommand<AutomationList> (*gc->alist().get(), &before, &after));
4328         }
4329
4330         /* gain automation */
4331         {
4332                 boost::shared_ptr<AutomationControl> gc = _trim->gain_control();
4333
4334                 XMLNode &before = gc->alist()->get_state ();
4335                 gc->alist()->shift (pos, frames);
4336                 XMLNode &after = gc->alist()->get_state ();
4337                 _session.add_command (new MementoCommand<AutomationList> (*gc->alist().get(), &before, &after));
4338         }
4339
4340         // TODO mute automation ??
4341
4342         /* pan automation */
4343         if (_pannable) {
4344                 ControlSet::Controls& c (_pannable->controls());
4345
4346                 for (ControlSet::Controls::const_iterator ci = c.begin(); ci != c.end(); ++ci) {
4347                         boost::shared_ptr<AutomationControl> pc = boost::dynamic_pointer_cast<AutomationControl> (ci->second);
4348                         if (pc) {
4349                                 boost::shared_ptr<AutomationList> al = pc->alist();
4350                                 XMLNode& before = al->get_state ();
4351                                 al->shift (pos, frames);
4352                                 XMLNode& after = al->get_state ();
4353                                 _session.add_command (new MementoCommand<AutomationList> (*al.get(), &before, &after));
4354                         }
4355                 }
4356         }
4357
4358         /* redirect automation */
4359         {
4360                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4361                 for (ProcessorList::iterator i = _processors.begin (); i != _processors.end (); ++i) {
4362
4363                         set<Evoral::Parameter> parameters = (*i)->what_can_be_automated();
4364
4365                         for (set<Evoral::Parameter>::const_iterator p = parameters.begin (); p != parameters.end (); ++p) {
4366                                 boost::shared_ptr<AutomationControl> ac = (*i)->automation_control (*p);
4367                                 if (ac) {
4368                                         boost::shared_ptr<AutomationList> al = ac->alist();
4369                                         XMLNode &before = al->get_state ();
4370                                         al->shift (pos, frames);
4371                                         XMLNode &after = al->get_state ();
4372                                         _session.add_command (new MementoCommand<AutomationList> (*al.get(), &before, &after));
4373                                 }
4374                         }
4375                 }
4376         }
4377 }
4378
4379 void
4380 Route::set_plugin_state_dir (boost::weak_ptr<Processor> p, const std::string& d)
4381 {
4382         boost::shared_ptr<Processor> processor (p.lock ());
4383         boost::shared_ptr<PluginInsert> pi  = boost::dynamic_pointer_cast<PluginInsert> (processor);
4384         if (!pi) {
4385                 return;
4386         }
4387         pi->set_state_dir (d);
4388 }
4389
4390 int
4391 Route::save_as_template (const string& path, const string& name)
4392 {
4393         std::string state_dir = path.substr (0, path.find_last_of ('.')); // strip template_suffix
4394         PBD::Unwinder<std::string> uw (_session._template_state_dir, state_dir);
4395
4396         XMLNode& node (state (false));
4397
4398         XMLTree tree;
4399
4400         IO::set_name_in_state (*node.children().front(), name);
4401
4402         tree.set_root (&node);
4403
4404         /* return zero on success, non-zero otherwise */
4405         return !tree.write (path.c_str());
4406 }
4407
4408
4409 bool
4410 Route::set_name (const string& str)
4411 {
4412         if (str == name()) {
4413                 return true;
4414         }
4415
4416         string name = Route::ensure_track_or_route_name (str, _session);
4417         SessionObject::set_name (name);
4418
4419         bool ret = (_input->set_name(name) && _output->set_name(name));
4420
4421         if (ret) {
4422                 /* rename the main outs. Leave other IO processors
4423                  * with whatever name they already have, because its
4424                  * just fine as it is (it will not contain the route
4425                  * name if its a port insert, port send or port return).
4426                  */
4427
4428                 if (_main_outs) {
4429                         if (_main_outs->set_name (name)) {
4430                                 /* XXX returning false here is stupid because
4431                                    we already changed the route name.
4432                                 */
4433                                 return false;
4434                         }
4435                 }
4436         }
4437
4438         return ret;
4439 }
4440
4441 /** Set the name of a route in an XML description.
4442  *  @param node XML <Route> node to set the name in.
4443  *  @param name New name.
4444  */
4445 void
4446 Route::set_name_in_state (XMLNode& node, string const & name, bool rename_playlist)
4447 {
4448         node.add_property (X_("name"), name);
4449
4450         XMLNodeList children = node.children();
4451         for (XMLNodeIterator i = children.begin(); i != children.end(); ++i) {
4452
4453                 if ((*i)->name() == X_("IO")) {
4454
4455                         IO::set_name_in_state (**i, name);
4456
4457                 } else if ((*i)->name() == X_("Processor")) {
4458
4459                         XMLProperty* role = (*i)->property (X_("role"));
4460                         if (role && role->value() == X_("Main")) {
4461                                 (*i)->add_property (X_("name"), name);
4462                         }
4463
4464                 } else if ((*i)->name() == X_("Diskstream")) {
4465
4466                         if (rename_playlist) {
4467                                 (*i)->add_property (X_("playlist"), string_compose ("%1.1", name).c_str());
4468                         }
4469                         (*i)->add_property (X_("name"), name);
4470
4471                 }
4472         }
4473 }
4474
4475 boost::shared_ptr<Send>
4476 Route::internal_send_for (boost::shared_ptr<const Route> target) const
4477 {
4478         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4479
4480         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4481                 boost::shared_ptr<InternalSend> send;
4482
4483                 if ((send = boost::dynamic_pointer_cast<InternalSend>(*i)) != 0) {
4484                         if (send->target_route() == target) {
4485                                 return send;
4486                         }
4487                 }
4488         }
4489
4490         return boost::shared_ptr<Send>();
4491 }
4492
4493 /** @param c Audio channel index.
4494  *  @param yn true to invert phase, otherwise false.
4495  */
4496 void
4497 Route::set_phase_invert (uint32_t c, bool yn)
4498 {
4499         if (_phase_invert[c] != yn) {
4500                 _phase_invert[c] = yn;
4501                 phase_invert_changed (); /* EMIT SIGNAL */
4502                 _phase_control->Changed(); /* EMIT SIGNAL */
4503                 _session.set_dirty ();
4504         }
4505 }
4506
4507 void
4508 Route::set_phase_invert (boost::dynamic_bitset<> p)
4509 {
4510         if (_phase_invert != p) {
4511                 _phase_invert = p;
4512                 phase_invert_changed (); /* EMIT SIGNAL */
4513                 _session.set_dirty ();
4514         }
4515 }
4516
4517 bool
4518 Route::phase_invert (uint32_t c) const
4519 {
4520         return _phase_invert[c];
4521 }
4522
4523 boost::dynamic_bitset<>
4524 Route::phase_invert () const
4525 {
4526         return _phase_invert;
4527 }
4528
4529 void
4530 Route::set_denormal_protection (bool yn)
4531 {
4532         if (_denormal_protection != yn) {
4533                 _denormal_protection = yn;
4534                 denormal_protection_changed (); /* EMIT SIGNAL */
4535         }
4536 }
4537
4538 bool
4539 Route::denormal_protection () const
4540 {
4541         return _denormal_protection;
4542 }
4543
4544 void
4545 Route::set_active (bool yn, void* src)
4546 {
4547         if (_session.transport_rolling()) {
4548                 return;
4549         }
4550
4551         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_route_active()) {
4552                 _route_group->foreach_route (boost::bind (&Route::set_active, _1, yn, _route_group));
4553                 return;
4554         }
4555
4556         if (_active != yn) {
4557                 _active = yn;
4558                 _input->set_active (yn);
4559                 _output->set_active (yn);
4560                 active_changed (); // EMIT SIGNAL
4561                 _session.set_dirty ();
4562         }
4563 }
4564
4565 boost::shared_ptr<Pannable>
4566 Route::pannable() const
4567 {
4568         return _pannable;
4569 }
4570
4571 boost::shared_ptr<Panner>
4572 Route::panner() const
4573 {
4574         /* may be null ! */
4575         return _main_outs->panner_shell()->panner();
4576 }
4577
4578 boost::shared_ptr<PannerShell>
4579 Route::panner_shell() const
4580 {
4581         return _main_outs->panner_shell();
4582 }
4583
4584 boost::shared_ptr<GainControl>
4585 Route::gain_control() const
4586 {
4587         return _gain_control;
4588 }
4589
4590 boost::shared_ptr<GainControl>
4591 Route::trim_control() const
4592 {
4593         return _trim_control;
4594 }
4595
4596 boost::shared_ptr<Route::PhaseControllable>
4597 Route::phase_control() const
4598 {
4599         if (phase_invert().size()) {
4600                 return _phase_control;
4601         } else {
4602                 return boost::shared_ptr<PhaseControllable>();
4603         }
4604 }
4605
4606 boost::shared_ptr<AutomationControl>
4607 Route::get_control (const Evoral::Parameter& param)
4608 {
4609         /* either we own the control or .... */
4610
4611         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(control (param));
4612
4613         if (!c) {
4614
4615                 /* maybe one of our processors does or ... */
4616
4617                 Glib::Threads::RWLock::ReaderLock rm (_processor_lock);
4618                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4619                         if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->control (param))) != 0) {
4620                                 break;
4621                         }
4622                 }
4623         }
4624
4625         if (!c) {
4626
4627                 /* nobody does so we'll make a new one */
4628
4629                 c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
4630                 add_control(c);
4631         }
4632
4633         return c;
4634 }
4635
4636 boost::shared_ptr<Processor>
4637 Route::nth_plugin (uint32_t n) const
4638 {
4639         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4640         ProcessorList::const_iterator i;
4641
4642         for (i = _processors.begin(); i != _processors.end(); ++i) {
4643                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
4644                         if (n-- == 0) {
4645                                 return *i;
4646                         }
4647                 }
4648         }
4649
4650         return boost::shared_ptr<Processor> ();
4651 }
4652
4653 boost::shared_ptr<Processor>
4654 Route::nth_send (uint32_t n) const
4655 {
4656         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4657         ProcessorList::const_iterator i;
4658
4659         for (i = _processors.begin(); i != _processors.end(); ++i) {
4660                 if (boost::dynamic_pointer_cast<Send> (*i)) {
4661
4662                         if ((*i)->name().find (_("Monitor")) == 0) {
4663                                 /* send to monitor section is not considered
4664                                    to be an accessible send.
4665                                 */
4666                                 continue;
4667                         }
4668
4669                         if (n-- == 0) {
4670                                 return *i;
4671                         }
4672                 }
4673         }
4674
4675         return boost::shared_ptr<Processor> ();
4676 }
4677
4678 bool
4679 Route::has_io_processor_named (const string& name)
4680 {
4681         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4682         ProcessorList::iterator i;
4683
4684         for (i = _processors.begin(); i != _processors.end(); ++i) {
4685                 if (boost::dynamic_pointer_cast<Send> (*i) ||
4686                     boost::dynamic_pointer_cast<PortInsert> (*i)) {
4687                         if ((*i)->name() == name) {
4688                                 return true;
4689                         }
4690                 }
4691         }
4692
4693         return false;
4694 }
4695
4696 MuteMaster::MutePoint
4697 Route::mute_points () const
4698 {
4699         return _mute_master->mute_points ();
4700 }
4701
4702 void
4703 Route::set_processor_positions ()
4704 {
4705         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4706
4707         bool had_amp = false;
4708         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4709                 (*i)->set_pre_fader (!had_amp);
4710                 if (*i == _amp) {
4711                         had_amp = true;
4712                 }
4713         }
4714 }
4715
4716 /** Called when there is a proposed change to the input port count */
4717 bool
4718 Route::input_port_count_changing (ChanCount to)
4719 {
4720         list<pair<ChanCount, ChanCount> > c = try_configure_processors (to, 0);
4721         if (c.empty()) {
4722                 /* The processors cannot be configured with the new input arrangement, so
4723                    block the change.
4724                 */
4725                 return true;
4726         }
4727
4728         /* The change is ok */
4729         return false;
4730 }
4731
4732 /** Called when there is a proposed change to the output port count */
4733 bool
4734 Route::output_port_count_changing (ChanCount to)
4735 {
4736         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4737                 if (processor_out_streams.get(*t) > to.get(*t)) {
4738                         return true;
4739                 }
4740         }
4741         /* The change is ok */
4742         return false;
4743 }
4744
4745 list<string>
4746 Route::unknown_processors () const
4747 {
4748         list<string> p;
4749
4750         if (_session.get_disable_all_loaded_plugins ()) {
4751                 // Do not list "missing plugins" if they are explicitly disabled
4752                 return p;
4753         }
4754
4755         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
4756         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4757                 if (boost::dynamic_pointer_cast<UnknownProcessor const> (*i)) {
4758                         p.push_back ((*i)->name ());
4759                 }
4760         }
4761
4762         return p;
4763 }
4764
4765
4766 framecnt_t
4767 Route::update_port_latencies (PortSet& from, PortSet& to, bool playback, framecnt_t our_latency) const
4768 {
4769         /* we assume that all our input ports feed all our output ports. its not
4770            universally true, but the alternative is way too corner-case to worry about.
4771         */
4772
4773         LatencyRange all_connections;
4774
4775         if (from.empty()) {
4776                 all_connections.min = 0;
4777                 all_connections.max = 0;
4778         } else {
4779                 all_connections.min = ~((pframes_t) 0);
4780                 all_connections.max = 0;
4781
4782                 /* iterate over all "from" ports and determine the latency range for all of their
4783                    connections to the "outside" (outside of this Route).
4784                 */
4785
4786                 for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
4787
4788                         LatencyRange range;
4789
4790                         p->get_connected_latency_range (range, playback);
4791
4792                         all_connections.min = min (all_connections.min, range.min);
4793                         all_connections.max = max (all_connections.max, range.max);
4794                 }
4795         }
4796
4797         /* set the "from" port latencies to the max/min range of all their connections */
4798
4799         for (PortSet::iterator p = from.begin(); p != from.end(); ++p) {
4800                 p->set_private_latency_range (all_connections, playback);
4801         }
4802
4803         /* set the ports "in the direction of the flow" to the same value as above plus our own signal latency */
4804
4805         all_connections.min += our_latency;
4806         all_connections.max += our_latency;
4807
4808         for (PortSet::iterator p = to.begin(); p != to.end(); ++p) {
4809                 p->set_private_latency_range (all_connections, playback);
4810         }
4811
4812         return all_connections.max;
4813 }
4814
4815 framecnt_t
4816 Route::set_private_port_latencies (bool playback) const
4817 {
4818         framecnt_t own_latency = 0;
4819
4820         /* Processor list not protected by lock: MUST BE CALLED FROM PROCESS THREAD
4821            OR LATENCY CALLBACK.
4822
4823            This is called (early) from the latency callback. It computes the REAL
4824            latency associated with each port and stores the result as the "private"
4825            latency of the port. A later call to Route::set_public_port_latencies()
4826            sets all ports to the same value to reflect the fact that we do latency
4827            compensation and so all signals are delayed by the same amount as they
4828            flow through ardour.
4829         */
4830
4831         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
4832                 if ((*i)->active ()) {
4833                         own_latency += (*i)->signal_latency ();
4834                 }
4835         }
4836
4837         if (playback) {
4838                 /* playback: propagate latency from "outside the route" to outputs to inputs */
4839                 return update_port_latencies (_output->ports (), _input->ports (), true, own_latency);
4840         } else {
4841                 /* capture: propagate latency from "outside the route" to inputs to outputs */
4842                 return update_port_latencies (_input->ports (), _output->ports (), false, own_latency);
4843         }
4844 }
4845
4846 void
4847 Route::set_public_port_latencies (framecnt_t value, bool playback) const
4848 {
4849         /* this is called to set the JACK-visible port latencies, which take
4850            latency compensation into account.
4851         */
4852
4853         LatencyRange range;
4854
4855         range.min = value;
4856         range.max = value;
4857
4858         {
4859                 const PortSet& ports (_input->ports());
4860                 for (PortSet::const_iterator p = ports.begin(); p != ports.end(); ++p) {
4861                         p->set_public_latency_range (range, playback);
4862                 }
4863         }
4864
4865         {
4866                 const PortSet& ports (_output->ports());
4867                 for (PortSet::const_iterator p = ports.begin(); p != ports.end(); ++p) {
4868                         p->set_public_latency_range (range, playback);
4869                 }
4870         }
4871 }
4872
4873 /** Put the invisible processors in the right place in _processors.
4874  *  Must be called with a writer lock on _processor_lock held.
4875  */
4876 #ifdef __clang__
4877 __attribute__((annotate("realtime")))
4878 #endif
4879 void
4880 Route::setup_invisible_processors ()
4881 {
4882 #ifndef NDEBUG
4883         Glib::Threads::RWLock::WriterLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
4884         assert (!lm.locked ());
4885 #endif
4886
4887         if (!_main_outs) {
4888                 /* too early to be doing this stuff */
4889                 return;
4890         }
4891
4892         /* we'll build this new list here and then use it
4893          *
4894          * TODO put the ProcessorList is on the stack for RT-safety.
4895          */
4896
4897         ProcessorList new_processors;
4898
4899         /* find visible processors */
4900
4901         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
4902                 if ((*i)->display_to_user ()) {
4903                         new_processors.push_back (*i);
4904                 }
4905         }
4906
4907         /* find the amp */
4908
4909         ProcessorList::iterator amp = new_processors.begin ();
4910         while (amp != new_processors.end() && *amp != _amp) {
4911                 ++amp;
4912         }
4913
4914         assert (amp != new_processors.end ());
4915
4916         /* and the processor after the amp */
4917
4918         ProcessorList::iterator after_amp = amp;
4919         ++after_amp;
4920
4921         /* METER */
4922
4923         if (_meter) {
4924                 switch (_meter_point) {
4925                 case MeterInput:
4926                         assert (!_meter->display_to_user ());
4927                         new_processors.push_front (_meter);
4928                         break;
4929                 case MeterPreFader:
4930                         assert (!_meter->display_to_user ());
4931                         new_processors.insert (amp, _meter);
4932                         break;
4933                 case MeterPostFader:
4934                         /* do nothing here */
4935                         break;
4936                 case MeterOutput:
4937                         /* do nothing here */
4938                         break;
4939                 case MeterCustom:
4940                         /* the meter is visible, so we don't touch it here */
4941                         break;
4942                 }
4943         }
4944
4945         /* MAIN OUTS */
4946
4947         assert (_main_outs);
4948         assert (!_main_outs->display_to_user ());
4949         new_processors.push_back (_main_outs);
4950
4951         /* iterator for the main outs */
4952
4953         ProcessorList::iterator main = new_processors.end();
4954         --main;
4955
4956         /* OUTPUT METERING */
4957
4958         if (_meter && (_meter_point == MeterOutput || _meter_point == MeterPostFader)) {
4959                 assert (!_meter->display_to_user ());
4960
4961                 /* add the processor just before or just after the main outs */
4962
4963                 ProcessorList::iterator meter_point = main;
4964
4965                 if (_meter_point == MeterOutput) {
4966                         ++meter_point;
4967                 }
4968                 new_processors.insert (meter_point, _meter);
4969         }
4970
4971         /* MONITOR SEND */
4972
4973         if (_monitor_send && !is_monitor ()) {
4974                 assert (!_monitor_send->display_to_user ());
4975                 switch (Config->get_listen_position ()) {
4976                 case PreFaderListen:
4977                         switch (Config->get_pfl_position ()) {
4978                         case PFLFromBeforeProcessors:
4979                                 new_processors.push_front (_monitor_send);
4980                                 break;
4981                         case PFLFromAfterProcessors:
4982                                 new_processors.insert (amp, _monitor_send);
4983                                 break;
4984                         }
4985                         _monitor_send->set_can_pan (false);
4986                         break;
4987                 case AfterFaderListen:
4988                         switch (Config->get_afl_position ()) {
4989                         case AFLFromBeforeProcessors:
4990                                 new_processors.insert (after_amp, _monitor_send);
4991                                 break;
4992                         case AFLFromAfterProcessors:
4993                                 new_processors.insert (new_processors.end(), _monitor_send);
4994                                 break;
4995                         }
4996                         _monitor_send->set_can_pan (true);
4997                         break;
4998                 }
4999         }
5000
5001 #if 0 // not used - just yet
5002         if (!is_master() && !is_monitor() && !is_auditioner()) {
5003                 new_processors.push_front (_delayline);
5004         }
5005 #endif
5006
5007         /* MONITOR CONTROL */
5008
5009         if (_monitor_control && is_monitor ()) {
5010                 assert (!_monitor_control->display_to_user ());
5011                 new_processors.insert (amp, _monitor_control);
5012         }
5013
5014         /* INTERNAL RETURN */
5015
5016         /* doing this here means that any monitor control will come just after
5017            the return.
5018         */
5019
5020         if (_intreturn) {
5021                 assert (!_intreturn->display_to_user ());
5022                 new_processors.push_front (_intreturn);
5023         }
5024
5025         if (_trim && _trim->active()) {
5026                 assert (!_trim->display_to_user ());
5027                 new_processors.push_front (_trim);
5028         }
5029         /* EXPORT PROCESSOR */
5030
5031         if (_capturing_processor) {
5032                 assert (!_capturing_processor->display_to_user ());
5033                 new_processors.push_front (_capturing_processor);
5034         }
5035
5036         _processors = new_processors;
5037
5038         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5039                 if (!(*i)->display_to_user () && !(*i)->active () && (*i) != _monitor_send) {
5040                         (*i)->activate ();
5041                 }
5042         }
5043
5044         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: setup_invisible_processors\n", _name));
5045         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5046                 DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1\n", (*i)->name ()));
5047         }
5048 }
5049
5050 void
5051 Route::unpan ()
5052 {
5053         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
5054         Glib::Threads::RWLock::ReaderLock lp (_processor_lock);
5055
5056         _pannable.reset ();
5057
5058         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5059                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery>(*i);
5060                 if (d) {
5061                         d->unpan ();
5062                 }
5063         }
5064 }
5065
5066 /** If the meter point is `Custom', make a note of where the meter is.
5067  *  This is so that if the meter point is subsequently set to something else,
5068  *  and then back to custom, we can put the meter back where it was last time
5069  *  custom was enabled.
5070  *
5071  *  Must be called with the _processor_lock held.
5072  */
5073 void
5074 Route::maybe_note_meter_position ()
5075 {
5076         if (_meter_point != MeterCustom) {
5077                 return;
5078         }
5079
5080         _custom_meter_position_noted = true;
5081         /* custom meter points range from after trim to before panner/main_outs
5082          * this is a limitation by the current processor UI
5083          */
5084         bool seen_trim = false;
5085         _processor_after_last_custom_meter.reset();
5086         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5087                 if ((*i) == _trim) {
5088                         seen_trim = true;
5089                 }
5090                 if ((*i) == _main_outs) {
5091                         _processor_after_last_custom_meter = *i;
5092                         break;
5093                 }
5094                 if (boost::dynamic_pointer_cast<PeakMeter> (*i)) {
5095                         if (!seen_trim) {
5096                                 _processor_after_last_custom_meter = _trim;
5097                         } else {
5098                                 ProcessorList::iterator j = i;
5099                                 ++j;
5100                                 assert(j != _processors.end ()); // main_outs should be before
5101                                 _processor_after_last_custom_meter = *j;
5102                         }
5103                         break;
5104                 }
5105         }
5106         assert(_processor_after_last_custom_meter.lock());
5107 }
5108
5109 boost::shared_ptr<Processor>
5110 Route::processor_by_id (PBD::ID id) const
5111 {
5112         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5113         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5114                 if ((*i)->id() == id) {
5115                         return *i;
5116                 }
5117         }
5118
5119         return boost::shared_ptr<Processor> ();
5120 }
5121
5122 /** @return the monitoring state, or in other words what data we are pushing
5123  *  into the route (data from the inputs, data from disk or silence)
5124  */
5125 MonitorState
5126 Route::monitoring_state () const
5127 {
5128         return MonitoringInput;
5129 }
5130
5131 /** @return what we should be metering; either the data coming from the input
5132  *  IO or the data that is flowing through the route.
5133  */
5134 MeterState
5135 Route::metering_state () const
5136 {
5137         return MeteringRoute;
5138 }
5139
5140 bool
5141 Route::has_external_redirects () const
5142 {
5143         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5144
5145                 /* ignore inactive processors and obviously ignore the main
5146                  * outs since everything has them and we don't care.
5147                  */
5148
5149                 if ((*i)->active() && (*i) != _main_outs && (*i)->does_routing()) {
5150                         return true;;
5151                 }
5152         }
5153
5154         return false;
5155 }
5156
5157 boost::shared_ptr<Processor>
5158 Route::the_instrument () const
5159 {
5160         Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5161         return the_instrument_unlocked ();
5162 }
5163
5164 boost::shared_ptr<Processor>
5165 Route::the_instrument_unlocked () const
5166 {
5167         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
5168                 if (boost::dynamic_pointer_cast<PluginInsert>(*i)) {
5169                         if ((*i)->input_streams().n_midi() > 0 &&
5170                             (*i)->output_streams().n_audio() > 0) {
5171                                 return (*i);
5172                         }
5173                 }
5174         }
5175         return boost::shared_ptr<Processor>();
5176 }
5177
5178
5179
5180 void
5181 Route::non_realtime_locate (framepos_t pos)
5182 {
5183         if (_pannable) {
5184                 _pannable->transport_located (pos);
5185         }
5186
5187         if (_delayline.get()) {
5188                 _delayline.get()->flush();
5189         }
5190
5191         {
5192                 //Glib::Threads::Mutex::Lock lx (AudioEngine::instance()->process_lock ());
5193                 Glib::Threads::RWLock::ReaderLock lm (_processor_lock);
5194
5195                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
5196                         (*i)->transport_located (pos);
5197                 }
5198         }
5199         _roll_delay = _initial_delay;
5200 }
5201
5202 void
5203 Route::fill_buffers_with_input (BufferSet& bufs, boost::shared_ptr<IO> io, pframes_t nframes)
5204 {
5205         size_t n_buffers;
5206         size_t i;
5207
5208         /* MIDI
5209          *
5210          * We don't currently mix MIDI input together, so we don't need the
5211          * complex logic of the audio case.
5212          */
5213
5214         n_buffers = bufs.count().n_midi ();
5215
5216         for (i = 0; i < n_buffers; ++i) {
5217
5218                 boost::shared_ptr<MidiPort> source_port = io->midi (i);
5219                 MidiBuffer& buf (bufs.get_midi (i));
5220
5221                 if (source_port) {
5222                         buf.copy (source_port->get_midi_buffer(nframes));
5223                 } else {
5224                         buf.silence (nframes);
5225                 }
5226         }
5227
5228         /* AUDIO */
5229
5230         n_buffers = bufs.count().n_audio();
5231
5232         size_t n_ports = io->n_ports().n_audio();
5233         float scaling = 1.0f;
5234
5235         if (n_ports > n_buffers) {
5236                 scaling = ((float) n_buffers) / n_ports;
5237         }
5238
5239         for (i = 0; i < n_ports; ++i) {
5240
5241                 /* if there are more ports than buffers, map them onto buffers
5242                  * in a round-robin fashion
5243                  */
5244
5245                 boost::shared_ptr<AudioPort> source_port = io->audio (i);
5246                 AudioBuffer& buf (bufs.get_audio (i%n_buffers));
5247
5248
5249                 if (i < n_buffers) {
5250
5251                         /* first time through just copy a channel into
5252                            the output buffer.
5253                         */
5254
5255                         buf.read_from (source_port->get_audio_buffer (nframes), nframes);
5256
5257                         if (scaling != 1.0f) {
5258                                 buf.apply_gain (scaling, nframes);
5259                         }
5260
5261                 } else {
5262
5263                         /* on subsequent times around, merge data from
5264                          * the port with what is already there
5265                          */
5266
5267                         if (scaling != 1.0f) {
5268                                 buf.accumulate_with_gain_from (source_port->get_audio_buffer (nframes), nframes, 0, scaling);
5269                         } else {
5270                                 buf.accumulate_from (source_port->get_audio_buffer (nframes), nframes);
5271                         }
5272                 }
5273         }
5274
5275         /* silence any remaining buffers */
5276
5277         for (; i < n_buffers; ++i) {
5278                 AudioBuffer& buf (bufs.get_audio (i));
5279                 buf.silence (nframes);
5280         }
5281
5282         /* establish the initial setup of the buffer set, reflecting what was
5283            copied into it. unless, of course, we are the auditioner, in which
5284            case nothing was fed into it from the inputs at all.
5285         */
5286
5287         if (!is_auditioner()) {
5288                 bufs.set_count (io->n_ports());
5289         }
5290 }
5291
5292 boost::shared_ptr<AutomationControl>
5293 Route::pan_azimuth_control() const
5294 {
5295 #ifdef MIXBUS
5296         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5297         if (!plug) {
5298                 return boost::shared_ptr<AutomationControl>();
5299         }
5300         const uint32_t port_channel_post_pan = 2; // gtk2_ardour/mixbus_ports.h
5301         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_channel_post_pan)));
5302 #else
5303         if (!_pannable || !panner()) {
5304                 return boost::shared_ptr<AutomationControl>();
5305         }
5306         return _pannable->pan_azimuth_control;
5307 #endif
5308 }
5309
5310 boost::shared_ptr<AutomationControl>
5311 Route::pan_elevation_control() const
5312 {
5313         if (Profile->get_mixbus() || !_pannable || !panner()) {
5314                 return boost::shared_ptr<AutomationControl>();
5315         }
5316
5317         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5318
5319         if (c.find (PanElevationAutomation) != c.end()) {
5320                 return _pannable->pan_elevation_control;
5321         } else {
5322                 return boost::shared_ptr<AutomationControl>();
5323         }
5324 }
5325 boost::shared_ptr<AutomationControl>
5326 Route::pan_width_control() const
5327 {
5328         if (Profile->get_mixbus() || !_pannable || !panner()) {
5329                 return boost::shared_ptr<AutomationControl>();
5330         }
5331
5332         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5333
5334         if (c.find (PanWidthAutomation) != c.end()) {
5335                 return _pannable->pan_width_control;
5336         } else {
5337                 return boost::shared_ptr<AutomationControl>();
5338         }
5339 }
5340 boost::shared_ptr<AutomationControl>
5341 Route::pan_frontback_control() const
5342 {
5343         if (Profile->get_mixbus() || !_pannable || !panner()) {
5344                 return boost::shared_ptr<AutomationControl>();
5345         }
5346
5347         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5348
5349         if (c.find (PanFrontBackAutomation) != c.end()) {
5350                 return _pannable->pan_frontback_control;
5351         } else {
5352                 return boost::shared_ptr<AutomationControl>();
5353         }
5354 }
5355 boost::shared_ptr<AutomationControl>
5356 Route::pan_lfe_control() const
5357 {
5358         if (Profile->get_mixbus() || !_pannable || !panner()) {
5359                 return boost::shared_ptr<AutomationControl>();
5360         }
5361
5362         set<Evoral::Parameter> c = panner()->what_can_be_automated ();
5363
5364         if (c.find (PanLFEAutomation) != c.end()) {
5365                 return _pannable->pan_lfe_control;
5366         } else {
5367                 return boost::shared_ptr<AutomationControl>();
5368         }
5369 }
5370
5371 uint32_t
5372 Route::eq_band_cnt () const
5373 {
5374         if (Profile->get_mixbus()) {
5375                 return 3;
5376         } else {
5377                 /* Ardour has no well-known EQ object */
5378                 return 0;
5379         }
5380 }
5381
5382 boost::shared_ptr<AutomationControl>
5383 Route::eq_gain_controllable (uint32_t band) const
5384 {
5385 #ifdef MIXBUS
5386         boost::shared_ptr<PluginInsert> eq = ch_eq();
5387
5388         if (!eq) {
5389                 return boost::shared_ptr<AutomationControl>();
5390         }
5391
5392         uint32_t port_number;
5393         switch (band) {
5394         case 0:
5395                 if (is_master() || mixbus()) {
5396                         port_number = 4;
5397                 } else {
5398                         port_number = 8;
5399                 }
5400                 break;
5401         case 1:
5402                 if (is_master() || mixbus()) {
5403                         port_number = 3;
5404                 } else {
5405                         port_number = 6;
5406                 }
5407                 break;
5408         case 2:
5409                 if (is_master() || mixbus()) {
5410                         port_number = 2;
5411                 } else {
5412                         port_number = 4;
5413                 }
5414                 break;
5415         default:
5416                 return boost::shared_ptr<AutomationControl>();
5417         }
5418
5419         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_number)));
5420 #else
5421         return boost::shared_ptr<AutomationControl>();
5422 #endif
5423 }
5424 boost::shared_ptr<AutomationControl>
5425 Route::eq_freq_controllable (uint32_t band) const
5426 {
5427 #ifdef MIXBUS
5428
5429         if (mixbus() || is_master()) {
5430                 /* no frequency controls for mixbusses or master */
5431                 return boost::shared_ptr<AutomationControl>();
5432         }
5433
5434         boost::shared_ptr<PluginInsert> eq = ch_eq();
5435
5436         if (!eq) {
5437                 return boost::shared_ptr<AutomationControl>();
5438         }
5439
5440         uint32_t port_number;
5441         switch (band) {
5442         case 0:
5443                 port_number = 7;
5444                 break;
5445         case 1:
5446                 port_number = 5;
5447                 break;
5448         case 2:
5449                 port_number = 3;
5450                 break;
5451         default:
5452                 return boost::shared_ptr<AutomationControl>();
5453         }
5454
5455         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_number)));
5456 #else
5457         return boost::shared_ptr<AutomationControl>();
5458 #endif
5459 }
5460
5461 boost::shared_ptr<AutomationControl>
5462 Route::eq_q_controllable (uint32_t band) const
5463 {
5464         return boost::shared_ptr<AutomationControl>();
5465 }
5466
5467 boost::shared_ptr<AutomationControl>
5468 Route::eq_shape_controllable (uint32_t band) const
5469 {
5470         return boost::shared_ptr<AutomationControl>();
5471 }
5472
5473 boost::shared_ptr<AutomationControl>
5474 Route::eq_enable_controllable () const
5475 {
5476 #ifdef MIXBUS
5477         boost::shared_ptr<PluginInsert> eq = ch_eq();
5478
5479         if (!eq) {
5480                 return boost::shared_ptr<AutomationControl>();
5481         }
5482
5483         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 1)));
5484 #else
5485         return boost::shared_ptr<AutomationControl>();
5486 #endif
5487 }
5488
5489 boost::shared_ptr<AutomationControl>
5490 Route::eq_hpf_controllable () const
5491 {
5492 #ifdef MIXBUS
5493         boost::shared_ptr<PluginInsert> eq = ch_eq();
5494
5495         if (!eq) {
5496                 return boost::shared_ptr<AutomationControl>();
5497         }
5498
5499         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (eq->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 2)));
5500 #else
5501         return boost::shared_ptr<AutomationControl>();
5502 #endif
5503 }
5504
5505 string
5506 Route::eq_band_name (uint32_t band) const
5507 {
5508         if (Profile->get_mixbus()) {
5509                 switch (band) {
5510                 case 0:
5511                         return _("lo");
5512                 case 1:
5513                         return _("mid");
5514                 case 2:
5515                         return _("hi");
5516                 default:
5517                         return string();
5518                 }
5519         } else {
5520                 return string ();
5521         }
5522 }
5523
5524 boost::shared_ptr<AutomationControl>
5525 Route::comp_enable_controllable () const
5526 {
5527 #ifdef MIXBUS
5528         boost::shared_ptr<PluginInsert> comp = ch_comp();
5529
5530         if (!comp) {
5531                 return boost::shared_ptr<AutomationControl>();
5532         }
5533
5534         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 1)));
5535 #else
5536         return boost::shared_ptr<AutomationControl>();
5537 #endif
5538 }
5539 boost::shared_ptr<AutomationControl>
5540 Route::comp_threshold_controllable () const
5541 {
5542 #ifdef MIXBUS
5543         boost::shared_ptr<PluginInsert> comp = ch_comp();
5544
5545         if (!comp) {
5546                 return boost::shared_ptr<AutomationControl>();
5547         }
5548
5549         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 2)));
5550
5551 #else
5552         return boost::shared_ptr<AutomationControl>();
5553 #endif
5554 }
5555 boost::shared_ptr<AutomationControl>
5556 Route::comp_speed_controllable () const
5557 {
5558 #ifdef MIXBUS
5559         boost::shared_ptr<PluginInsert> comp = ch_comp();
5560
5561         if (!comp) {
5562                 return boost::shared_ptr<AutomationControl>();
5563         }
5564
5565         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 3)));
5566 #else
5567         return boost::shared_ptr<AutomationControl>();
5568 #endif
5569 }
5570 boost::shared_ptr<AutomationControl>
5571 Route::comp_mode_controllable () const
5572 {
5573 #ifdef MIXBUS
5574         boost::shared_ptr<PluginInsert> comp = ch_comp();
5575
5576         if (!comp) {
5577                 return boost::shared_ptr<AutomationControl>();
5578         }
5579
5580         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 4)));
5581 #else
5582         return boost::shared_ptr<AutomationControl>();
5583 #endif
5584 }
5585 boost::shared_ptr<AutomationControl>
5586 Route::comp_makeup_controllable () const
5587 {
5588 #ifdef MIXBUS
5589         boost::shared_ptr<PluginInsert> comp = ch_comp();
5590
5591         if (!comp) {
5592                 return boost::shared_ptr<AutomationControl>();
5593         }
5594
5595         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 5)));
5596 #else
5597         return boost::shared_ptr<AutomationControl>();
5598 #endif
5599 }
5600 boost::shared_ptr<AutomationControl>
5601 Route::comp_redux_controllable () const
5602 {
5603 #ifdef MIXBUS
5604         boost::shared_ptr<PluginInsert> comp = ch_comp();
5605
5606         if (!comp) {
5607                 return boost::shared_ptr<AutomationControl>();
5608         }
5609
5610         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (comp->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, 6)));
5611 #else
5612         return boost::shared_ptr<AutomationControl>();
5613 #endif
5614 }
5615
5616 string
5617 Route::comp_mode_name (uint32_t mode) const
5618 {
5619 #ifdef MIXBUS
5620         switch (mode) {
5621         case 0:
5622                 return _("Leveler");
5623         case 1:
5624                 return _("Compressor");
5625         case 2:
5626                 return _("Limiter");
5627         case 3:
5628                 return mixbus() ? _("Sidechain") : _("Limiter");
5629         }
5630
5631         return _("???");
5632 #else
5633         return _("???");
5634 #endif
5635 }
5636
5637 string
5638 Route::comp_speed_name (uint32_t mode) const
5639 {
5640 #ifdef MIXBUS
5641         switch (mode) {
5642         case 0:
5643                 return _("Attk");
5644         case 1:
5645                 return _("Ratio");
5646         case 2:
5647         case 3:
5648                 return _("Rels");
5649         }
5650         return _("???");
5651 #else
5652         return _("???");
5653 #endif
5654 }
5655
5656 boost::shared_ptr<AutomationControl>
5657 Route::send_level_controllable (uint32_t n) const
5658 {
5659 #ifdef  MIXBUS
5660         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5661         if (!plug) {
5662                 return boost::shared_ptr<AutomationControl>();
5663         }
5664
5665         if (n >= 8) {
5666                 /* no such bus */
5667                 return boost::shared_ptr<AutomationControl>();
5668         }
5669
5670         const uint32_t port_id = port_channel_post_aux1_level + (2*n); // gtk2_ardour/mixbus_ports.h
5671         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_id)));
5672 #else
5673         boost::shared_ptr<Send> s = boost::dynamic_pointer_cast<Send>(nth_send (n));
5674         if (!s) {
5675                 return boost::shared_ptr<AutomationControl>();
5676         }
5677         return s->gain_control ();
5678 #endif
5679 }
5680
5681 boost::shared_ptr<AutomationControl>
5682 Route::send_enable_controllable (uint32_t n) const
5683 {
5684 #ifdef  MIXBUS
5685         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5686         if (!plug) {
5687                 return boost::shared_ptr<AutomationControl>();
5688         }
5689
5690         if (n >= 8) {
5691                 /* no such bus */
5692                 return boost::shared_ptr<AutomationControl>();
5693         }
5694
5695         const uint32_t port_id = port_channel_post_aux1_asgn + (2*n); // gtk2_ardour/mixbus_ports.h
5696         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_id)));
5697 #else
5698         /* although Ardour sends have enable/disable as part of the Processor
5699            API, it is not exposed as a controllable.
5700
5701            XXX: we should fix this.
5702         */
5703         return boost::shared_ptr<AutomationControl>();
5704 #endif
5705 }
5706
5707 string
5708 Route::send_name (uint32_t n) const
5709 {
5710 #ifdef MIXBUS
5711         if (n >= 8) {
5712                 return string();
5713         }
5714         boost::shared_ptr<Route> r = _session.get_mixbus (n);
5715         assert (r);
5716         return r->name();
5717 #else
5718         boost::shared_ptr<Processor> p = nth_send (n);
5719         if (p) {
5720                 return p->name();
5721         } else {
5722                 return string();
5723         }
5724 #endif
5725 }
5726
5727 boost::shared_ptr<AutomationControl>
5728 Route::master_send_enable_controllable () const
5729 {
5730 #ifdef  MIXBUS
5731         boost::shared_ptr<ARDOUR::PluginInsert> plug = ch_post();
5732         if (!plug) {
5733                 return boost::shared_ptr<AutomationControl>();
5734         }
5735         return boost::dynamic_pointer_cast<ARDOUR::AutomationControl> (plug->control (Evoral::Parameter (ARDOUR::PluginAutomation, 0, port_channel_post_mstr_assign)));
5736 #else
5737         return boost::shared_ptr<AutomationControl>();
5738 #endif
5739 }