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