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