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