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