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