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