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