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