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