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