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