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