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