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