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