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