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