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