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