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