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