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