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