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