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