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