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