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