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