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