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