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