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