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