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