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