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