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