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