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