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