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