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