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