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