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