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