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