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