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