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