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