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