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