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