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