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