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