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