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