eb0707044aa1191ddd0cc4b98cb97d6f01d8875f
[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 #include <cmath>
21 #include <fstream>
22 #include <cassert>
23 #include <algorithm>
24
25 #include "pbd/xml++.h"
26 #include "pbd/enumwriter.h"
27 #include "pbd/memento_command.h"
28 #include "pbd/stacktrace.h"
29
30 #include "evoral/Curve.hpp"
31
32 #include "ardour/amp.h"
33 #include "ardour/audio_port.h"
34 #include "ardour/audioengine.h"
35 #include "ardour/buffer.h"
36 #include "ardour/buffer_set.h"
37 #include "ardour/configuration.h"
38 #include "ardour/cycle_timer.h"
39 #include "ardour/debug.h"
40 #include "ardour/delivery.h"
41 #include "ardour/dB.h"
42 #include "ardour/internal_send.h"
43 #include "ardour/internal_return.h"
44 #include "ardour/ladspa_plugin.h"
45 #include "ardour/meter.h"
46 #include "ardour/mix.h"
47 #include "ardour/panner.h"
48 #include "ardour/plugin_insert.h"
49 #include "ardour/port.h"
50 #include "ardour/port_insert.h"
51 #include "ardour/processor.h"
52 #include "ardour/profile.h"
53 #include "ardour/route.h"
54 #include "ardour/route_group.h"
55 #include "ardour/send.h"
56 #include "ardour/session.h"
57 #include "ardour/timestamps.h"
58 #include "ardour/utils.h"
59
60 #include "i18n.h"
61
62 using namespace std;
63 using namespace ARDOUR;
64 using namespace PBD;
65
66 uint32_t Route::order_key_cnt = 0;
67 PBD::Signal1<void,string const&> Route::SyncOrderKeys;
68 PBD::Signal0<void> Route::RemoteControlIDChange;
69
70 Route::Route (Session& sess, string name, Flag flg, DataType default_type)
71         : SessionObject (sess, name)
72         , AutomatableControls (sess)
73         , _flags (flg)
74         , _solo_control (new SoloControllable (X_("solo"), *this))
75         , _mute_control (new MuteControllable (X_("mute"), *this))
76         , _mute_master (new MuteMaster (sess, name))
77         , _default_type (default_type)
78
79 {
80         init ();
81
82         /* add standard processors other than amp (added by ::init()) */
83
84         _meter.reset (new PeakMeter (_session));
85         _meter->set_display_to_user (false);
86         add_processor (_meter, PostFader);
87
88         if (_flags & ControlOut) {
89                 /* where we listen to tracks */
90                 _intreturn.reset (new InternalReturn (_session));
91                 add_processor (_intreturn, PreFader);
92         }
93
94         _main_outs.reset (new Delivery (_session, _output, _mute_master, _name, Delivery::Main));
95         add_processor (_main_outs, PostFader);
96
97         /* now that we have _meter, its safe to connect to this */
98
99         Metering::Meter.connect_same_thread (*this, (boost::bind (&Route::meter, this)));
100 }
101
102 Route::Route (Session& sess, const XMLNode& node, DataType default_type)
103         : SessionObject (sess, "toBeReset")
104         , AutomatableControls (sess)
105         , _solo_control (new SoloControllable (X_("solo"), *this))
106         , _mute_control (new MuteControllable (X_("mute"), *this))
107         , _mute_master (new MuteMaster (sess, "toBeReset"))
108         , _default_type (default_type)
109 {
110         init ();
111
112         _set_state (node, Stateful::loading_state_version, false);
113
114         /* now that we have _meter, its safe to connect to this */
115
116         Metering::Meter.connect_same_thread (*this, (boost::bind (&Route::meter, this)));
117 }
118
119 void
120 Route::init ()
121 {
122         _self_solo = false;
123         _soloed_by_others = 0;
124         _solo_isolated = 0;
125         _solo_safe = false;
126         _active = true;
127         processor_max_streams.reset();
128         _recordable = true;
129         order_keys[N_("signal")] = order_key_cnt++;
130         _silent = false;
131         _meter_point = MeterPostFader;
132         _initial_delay = 0;
133         _roll_delay = 0;
134         _have_internal_generator = false;
135         _declickable = false;
136         _pending_declick = true;
137         _remote_control_id = 0;
138         _in_configure_processors = false;
139         _mute_points = MuteMaster::AllPoints;
140
141         _phase_invert = 0;
142         _denormal_protection = false;
143
144         /* add standard controls */
145
146         _solo_control->set_flags (Controllable::Flag (_solo_control->flags() | Controllable::Toggle));
147         _mute_control->set_flags (Controllable::Flag (_solo_control->flags() | Controllable::Toggle));
148         
149         add_control (_solo_control);
150         add_control (_mute_control);
151
152         /* input and output objects */
153
154         _input.reset (new IO (_session, _name, IO::Input, _default_type));
155         _output.reset (new IO (_session, _name, IO::Output, _default_type));
156
157         _input->changed.connect_same_thread (*this, boost::bind (&Route::input_change_handler, this, _1, _2));
158         _output->changed.connect_same_thread (*this, boost::bind (&Route::output_change_handler, this, _1, _2));
159
160         /* add amp processor  */
161
162         _amp.reset (new Amp (_session, _mute_master));
163         add_processor (_amp, PostFader);
164 }
165
166 Route::~Route ()
167 {
168         DEBUG_TRACE (DEBUG::Destruction, string_compose ("route %1 destructor\n", _name));
169
170         /* do this early so that we don't get incoming signals as we are going through destruction 
171          */
172
173         drop_connections ();
174
175         /* don't use clear_processors here, as it depends on the session which may
176            be half-destroyed by now 
177         */
178
179         Glib::RWLock::WriterLock lm (_processor_lock);
180         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
181                 (*i)->drop_references ();
182         }
183
184         _processors.clear ();
185 }
186
187 void
188 Route::set_remote_control_id (uint32_t id, bool notify_class_listeners)
189 {
190         if (id != _remote_control_id) {
191                 _remote_control_id = id;
192                 RemoteControlIDChanged ();
193                 if (notify_class_listeners) {
194                         RemoteControlIDChange ();
195                 }
196         }
197 }
198
199 uint32_t
200 Route::remote_control_id() const
201 {
202         return _remote_control_id;
203 }
204
205 long
206 Route::order_key (std::string const & name) const
207 {
208         OrderKeys::const_iterator i = order_keys.find (name);
209         if (i == order_keys.end()) {
210                 return -1;
211         }
212
213         return i->second;
214 }
215
216 void
217 Route::set_order_key (std::string const & name, long n)
218 {
219         order_keys[name] = n;
220
221         if (Config->get_sync_all_route_ordering()) {
222                 for (OrderKeys::iterator x = order_keys.begin(); x != order_keys.end(); ++x) {
223                         x->second = n;
224                 }
225         }
226
227         _session.set_dirty ();
228 }
229
230 /** Set all order keys to be the same as that for `base', if such a key
231  *  exists in this route.
232  *  @param base Base key.
233  */
234 void
235 Route::sync_order_keys (std::string const & base)
236 {
237         if (order_keys.empty()) {
238                 return;
239         }
240
241         OrderKeys::iterator i;
242         uint32_t key;
243
244         if ((i = order_keys.find (base)) == order_keys.end()) {
245                 /* key doesn't exist, use the first existing key (during session initialization) */
246                 i = order_keys.begin();
247                 key = i->second;
248                 ++i;
249         } else {
250                 /* key exists - use it and reset all others (actually, itself included) */
251                 key = i->second;
252                 i = order_keys.begin();
253         }
254
255         for (; i != order_keys.end(); ++i) {
256                 i->second = key;
257         }
258 }
259
260 string
261 Route::ensure_track_or_route_name(string name, Session &session)
262 {
263         string newname = name;
264
265         while (session.route_by_name (newname) != NULL) {
266                 newname = bump_name_once (newname);
267         }
268
269         return newname;
270 }
271
272
273 void
274 Route::inc_gain (gain_t fraction, void *src)
275 {
276         _amp->inc_gain (fraction, src);
277 }
278
279 void
280 Route::set_gain (gain_t val, void *src)
281 {
282         if (src != 0 && _route_group && src != _route_group && _route_group->active_property (RouteGroup::Gain)) {
283
284                 if (_route_group->is_relative()) {
285
286                         gain_t usable_gain = _amp->gain();
287                         if (usable_gain < 0.000001f) {
288                                 usable_gain = 0.000001f;
289                         }
290
291                         gain_t delta = val;
292                         if (delta < 0.000001f) {
293                                 delta = 0.000001f;
294                         }
295
296                         delta -= usable_gain;
297
298                         if (delta == 0.0f)
299                                 return;
300
301                         gain_t factor = delta / usable_gain;
302
303                         if (factor > 0.0f) {
304                                 factor = _route_group->get_max_factor(factor);
305                                 if (factor == 0.0f) {
306                                         _amp->gain_control()->Changed(); /* EMIT SIGNAL */
307                                         return;
308                                 }
309                         } else {
310                                 factor = _route_group->get_min_factor(factor);
311                                 if (factor == 0.0f) {
312                                         _amp->gain_control()->Changed(); /* EMIT SIGNAL */
313                                         return;
314                                 }
315                         }
316
317                         _route_group->apply (&Route::inc_gain, factor, _route_group);
318
319                 } else {
320
321                         _route_group->apply (&Route::set_gain, val, _route_group);
322                 }
323
324                 return;
325         }
326
327         if (val == _amp->gain()) {
328                 return;
329         }
330
331         _amp->set_gain (val, src);
332 }
333
334 /** Process this route for one (sub) cycle (process thread)
335  *
336  * @param bufs Scratch buffers to use for the signal path
337  * @param start_frame Initial transport frame
338  * @param end_frame Final transport frame
339  * @param nframes Number of frames to output (to ports)
340  *
341  * Note that (end_frame - start_frame) may not be equal to nframes when the
342  * transport speed isn't 1.0 (eg varispeed).
343  */
344 void
345 Route::process_output_buffers (BufferSet& bufs,
346                                sframes_t start_frame, sframes_t end_frame, nframes_t nframes,
347                                bool /*with_processors*/, int declick)
348 {
349         bool monitor;
350
351         bufs.is_silent (false);
352
353         switch (Config->get_monitoring_model()) {
354         case HardwareMonitoring:
355         case ExternalMonitoring:
356                 monitor = !record_enabled() || (_session.config.get_auto_input() && !_session.actively_recording());
357                 break;
358         default:
359                 monitor = true;
360         }
361
362         if (!declick) {
363                 declick = _pending_declick;
364         }
365
366         /* figure out if we're going to use gain automation */
367         _amp->setup_gain_automation (start_frame, end_frame, nframes);
368
369
370         /* tell main outs what to do about monitoring */
371         _main_outs->no_outs_cuz_we_no_monitor (!monitor);
372
373
374         /* -------------------------------------------------------------------------------------------
375            GLOBAL DECLICK (for transport changes etc.)
376            ----------------------------------------------------------------------------------------- */
377
378         if (declick > 0) {
379                 Amp::apply_gain (bufs, nframes, 0.0, 1.0);
380         } else if (declick < 0) {
381                 Amp::apply_gain (bufs, nframes, 1.0, 0.0);
382         }
383
384         _pending_declick = 0;
385
386         /* -------------------------------------------------------------------------------------------
387            DENORMAL CONTROL/PHASE INVERT
388            ----------------------------------------------------------------------------------------- */
389
390         if (_phase_invert) {
391
392                 int chn = 0;
393
394                 if (_denormal_protection || Config->get_denormal_protection()) {
395
396                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i, ++chn) {
397                                 Sample* const sp = i->data();
398
399                                 if (_phase_invert & chn) {
400                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
401                                                 sp[nx]  = -sp[nx];
402                                                 sp[nx] += 1.0e-27f;
403                                         }
404                                 } else {
405                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
406                                                 sp[nx] += 1.0e-27f;
407                                         }
408                                 }
409                         }
410
411                 } else {
412
413                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i, ++chn) {
414                                 Sample* const sp = i->data();
415
416                                 if (_phase_invert & chn) {
417                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
418                                                 sp[nx] = -sp[nx];
419                                         }
420                                 }
421                         }
422                 }
423
424         } else {
425
426                 if (_denormal_protection || Config->get_denormal_protection()) {
427
428                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
429                                 Sample* const sp = i->data();
430                                 for (nframes_t nx = 0; nx < nframes; ++nx) {
431                                         sp[nx] += 1.0e-27f;
432                                 }
433                         }
434
435                 }
436         }
437
438         /* -------------------------------------------------------------------------------------------
439            and go ....
440            ----------------------------------------------------------------------------------------- */
441
442         Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
443
444         if (rm.locked()) {
445                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
446
447                         if (bufs.count() != (*i)->input_streams()) {
448                                 cerr << _name << " bufs = " << bufs.count()
449                                      << " input for " << (*i)->name() << " = " << (*i)->input_streams()
450                                      << endl;
451                         }
452                         assert (bufs.count() == (*i)->input_streams());
453
454                         (*i)->run (bufs, start_frame, end_frame, nframes, *i != _processors.back());
455                         bufs.set_count ((*i)->output_streams());
456                 }
457         }
458 }
459
460 ChanCount
461 Route::n_process_buffers ()
462 {
463         return max (_input->n_ports(), processor_max_streams);
464 }
465
466 void
467 Route::passthru (sframes_t start_frame, sframes_t end_frame, nframes_t nframes, int declick)
468 {
469         BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
470
471         _silent = false;
472
473         assert (bufs.available() >= _input->n_ports());
474
475         if (_input->n_ports() == ChanCount::ZERO) {
476                 silence (nframes);
477         }
478
479         bufs.set_count (_input->n_ports());
480
481         if (is_control() && _session.listening()) {
482
483                 /* control/monitor bus ignores input ports when something is
484                    feeding the listen "stream". data will "arrive" into the
485                    route from the intreturn processor element.
486                 */
487
488                 bufs.silence (nframes, 0);
489
490         } else {
491
492                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
493
494                         BufferSet::iterator o = bufs.begin(*t);
495                         PortSet& ports (_input->ports());
496
497                         for (PortSet::iterator i = ports.begin(*t); i != ports.end(*t); ++i, ++o) {
498                                 o->read_from (i->get_buffer(nframes), nframes);
499                         }
500                 }
501         }
502
503         write_out_of_band_data (bufs, start_frame, end_frame, nframes);
504         process_output_buffers (bufs, start_frame, end_frame, nframes, true, declick);
505 }
506
507 void
508 Route::passthru_silence (sframes_t start_frame, sframes_t end_frame, nframes_t nframes, int declick)
509 {
510         BufferSet& bufs (_session.get_silent_buffers (n_process_buffers()));
511         bufs.set_count (_input->n_ports());
512         write_out_of_band_data (bufs, start_frame, end_frame, nframes);
513         process_output_buffers (bufs, start_frame, end_frame, nframes, true, declick);
514 }
515
516 void
517 Route::set_listen (bool yn, void* src)
518 {
519         if (_control_outs) {
520                 if (yn != _control_outs->active()) {
521                         if (yn) {
522                                 _control_outs->activate ();
523                         } else {
524                                 _control_outs->deactivate ();
525                         }
526
527                         listen_changed (src); /* EMIT SIGNAL */
528                 }
529         }
530 }
531
532 bool
533 Route::listening () const
534 {
535         if (_control_outs) {
536                 return _control_outs->active ();
537         } else {
538                 return false;
539         }
540 }
541
542 void
543 Route::set_solo_safe (bool yn, void *src)
544 {
545         if (_solo_safe != yn) {
546                 _solo_safe = yn;
547                 solo_safe_changed (src);
548         } 
549 }
550
551 bool
552 Route::solo_safe() const
553 {
554         return _solo_safe;
555 }
556
557 void
558 Route::set_solo (bool yn, void *src)
559 {
560         if (_solo_safe) {
561                 return;
562         }
563
564         if (_route_group && src != _route_group && _route_group->active_property (RouteGroup::Solo)) {
565                 _route_group->apply (&Route::set_solo, yn, _route_group);
566                 return;
567         }
568
569         if (self_soloed() != yn) {
570                 set_self_solo (yn);
571                 set_delivery_solo ();
572                 solo_changed (src); /* EMIT SIGNAL */
573                 _solo_control->Changed (); /* EMIT SIGNAL */
574         }
575 }
576
577 void
578 Route::set_self_solo (bool yn)
579 {
580         _self_solo = yn;
581 }
582
583 void
584 Route::mod_solo_by_others (int32_t delta)
585 {
586         if (delta < 0) {
587                 if (_soloed_by_others >= (uint32_t) delta) {
588                         _soloed_by_others += delta;
589                 } else {
590                         _soloed_by_others = 0;
591                 }
592         } else {
593                 _soloed_by_others += delta;
594         }
595
596         set_delivery_solo ();
597 }
598
599 void
600 Route::set_delivery_solo ()
601 {
602         /* tell all delivery processors what the solo situation is, so that they keep
603            delivering even though Session::soloing() is true and they were not
604            explicitly soloed.
605         */
606
607         Glib::RWLock::ReaderLock rm (_processor_lock);
608         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
609                 boost::shared_ptr<Delivery> d;
610                 
611                 if ((d = boost::dynamic_pointer_cast<Delivery> (*i)) != 0) {
612                         d->set_solo_level (soloed ());
613                         d->set_solo_isolated (solo_isolated());
614                 }
615         }
616 }
617
618 void
619 Route::set_solo_isolated (bool yn, void *src)
620 {
621         if (is_master() || is_control() || is_hidden()) {
622                 return;
623         }
624
625         if (_route_group && src != _route_group && _route_group->active_property (RouteGroup::Solo)) {
626                 _route_group->apply (&Route::set_solo_isolated, yn, _route_group);
627                 return;
628         }
629         
630         /* forward propagate solo-isolate status to everything fed by this route, but not those via sends only */
631
632         boost::shared_ptr<RouteList> routes = _session.get_routes ();
633         for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
634                 bool sends_only;
635                 bool does_feed = feeds (*i, &sends_only);
636                 
637                 if (does_feed && !sends_only) {
638                         (*i)->set_solo_isolated (yn, (*i)->route_group());
639                 }
640         }
641
642         bool changed = false;
643
644         if (yn) {
645                 if (_solo_isolated == 0) {
646                         changed = true;
647                 }
648                 _solo_isolated++;
649         } else {
650                 changed = (_solo_isolated == 1);
651                 if (_solo_isolated > 0) {
652                         _solo_isolated--;
653                 }
654         }
655
656         if (changed) {
657                 set_delivery_solo ();
658                 solo_isolated_changed (src);
659         }
660 }
661
662 bool
663 Route::solo_isolated () const
664 {
665         return _solo_isolated > 0;
666 }
667
668 void
669 Route::set_mute_points (MuteMaster::MutePoint mp)
670 {
671         _mute_points = mp;
672         mute_points_changed (); /* EMIT SIGNAL */
673
674         if (_mute_master->muted()) {
675                 _mute_master->mute_at (_mute_points);
676                 mute_changed (this); /* EMIT SIGNAL */
677         }
678 }
679
680 void
681 Route::set_mute (bool yn, void *src)
682 {
683         if (_route_group && src != _route_group && _route_group->active_property (RouteGroup::Mute)) {
684                 _route_group->apply (&Route::set_mute, yn, _route_group);
685                 return;
686         }
687
688         if (muted() != yn) {
689                 if (yn) {
690                         _mute_master->mute_at (_mute_points);
691                 } else {
692                         _mute_master->clear_mute ();
693                 }
694
695                 mute_changed (src); /* EMIT SIGNAL */
696         }
697 }
698
699 bool
700 Route::muted() const
701 {
702         return _mute_master->muted ();
703 }
704
705 #if 0
706 static void
707 dump_processors(const string& name, const list<boost::shared_ptr<Processor> >& procs)
708 {
709         cerr << name << " {" << endl;
710         for (list<boost::shared_ptr<Processor> >::const_iterator p = procs.begin();
711                         p != procs.end(); ++p) {
712                 cerr << "\t" << (*p)->name() << " ID = " << (*p)->id() << endl;
713         }
714         cerr << "}" << endl;
715 }
716 #endif
717
718 int
719 Route::add_processor (boost::shared_ptr<Processor> processor, Placement placement, ProcessorStreams* err)
720 {
721         ProcessorList::iterator loc;
722
723         /* XXX this is not thread safe - we don't hold the lock across determining the iter
724            to add before and actually doing the insertion. dammit.
725         */
726
727         if (placement == PreFader) {
728                 /* generic pre-fader: insert immediately before the amp */
729                 loc = find (_processors.begin(), _processors.end(), _amp);
730         } else {
731                 /* generic post-fader: insert right before the main outs */
732                 loc = find (_processors.begin(), _processors.end(), _main_outs);
733         }
734
735         return add_processor (processor, loc, err);
736 }
737
738
739 /** Add a processor to the route.
740  * If @a iter is not NULL, it must point to an iterator in _processors and the new
741  * processor will be inserted immediately before this location.  Otherwise,
742  * @a position is used.
743  */
744 int
745 Route::add_processor (boost::shared_ptr<Processor> processor, ProcessorList::iterator iter, ProcessorStreams* err)
746 {
747         ChanCount old_pms = processor_max_streams;
748
749         if (!_session.engine().connected() || !processor) {
750                 return 1;
751         }
752
753         {
754                 Glib::RWLock::WriterLock lm (_processor_lock);
755
756                 boost::shared_ptr<PluginInsert> pi;
757                 boost::shared_ptr<PortInsert> porti;
758
759                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), processor);
760
761                 if (processor == _amp || processor == _meter || processor == _main_outs) {
762                         // Ensure only one of these are in the list at any time
763                         if (loc != _processors.end()) {
764                                 if (iter == loc) { // Already in place, do nothing
765                                         return 0;
766                                 } else { // New position given, relocate
767                                         _processors.erase (loc);
768                                 }
769                         }
770
771                 } else {
772                         if (loc != _processors.end()) {
773                                 cerr << "ERROR: Processor added to route twice!" << endl;
774                                 return 1;
775                         }
776
777                         loc = iter;
778                 }
779
780                 _processors.insert (loc, processor);
781
782                 // Set up processor list channels.  This will set processor->[input|output]_streams(),
783                 // configure redirect ports properly, etc.
784
785                 if (configure_processors_unlocked (err)) {
786                         ProcessorList::iterator ploc = loc;
787                         --ploc;
788                         _processors.erase(ploc);
789                         configure_processors_unlocked (0); // it worked before we tried to add it ...
790                         cerr << "configure failed\n";
791                         return -1;
792                 }
793
794                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(processor)) != 0) {
795
796                         if (pi->natural_input_streams() == ChanCount::ZERO) {
797                                 /* generator plugin */
798                                 _have_internal_generator = true;
799                         }
800
801                 }
802
803                 if (_control_outs != processor) {
804                         // XXX: do we want to emit the signal here ? change call order.
805                         processor->activate ();
806                 }
807
808                 processor->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false, false));
809
810                 _output->set_user_latency (0);
811         }
812
813         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
814
815         return 0;
816 }
817
818 bool
819 Route::add_processor_from_xml (const XMLNode& node, ProcessorList::iterator iter)
820 {
821         const XMLProperty *prop;
822
823         if (node.name() != "Processor") {
824                 return false;
825         }
826
827         try {
828                 if ((prop = node.property ("type")) != 0) {
829
830                         boost::shared_ptr<Processor> processor;
831
832                         if (prop->value() == "ladspa" || prop->value() == "Ladspa" ||
833                             prop->value() == "lv2" ||
834                             prop->value() == "vst" ||
835                             prop->value() == "audiounit") {
836
837                                 processor.reset (new PluginInsert(_session, node));
838
839                         } else if (prop->value() == "port") {
840
841                                 processor.reset (new PortInsert (_session, _mute_master, node));
842
843                         } else if (prop->value() == "send") {
844
845                                 processor.reset (new Send (_session, _mute_master, node));
846
847                         } else if (prop->value() == "meter") {
848
849                                 if (_meter) {
850                                         if (_meter->set_state (node, Stateful::loading_state_version)) {
851                                                 return false;
852                                         } else {
853                                                 return true;
854                                         }
855                                 }
856
857                                 _meter.reset (new PeakMeter (_session, node));
858                                 _meter->set_display_to_user (_meter_point == MeterCustom);
859                                 processor = _meter;
860
861                         } else if (prop->value() == "amp") {
862
863                                 /* amp always exists */
864
865                                 processor = _amp;
866                                 if (processor->set_state (node, Stateful::loading_state_version)) {
867                                         return false;
868                                 } else {
869                                         /* never any reason to add it */
870                                         return true;
871                                 }
872
873                         } else if (prop->value() == "intsend") {
874
875                                 processor.reset (new InternalSend (_session, _mute_master, node));
876
877                         } else if (prop->value() == "intreturn") {
878
879                                 if (_intreturn) {
880                                         if (_intreturn->set_state (node, Stateful::loading_state_version)) {
881                                                 return false;
882                                         } else {
883                                                 return true;
884                                         }
885                                 }
886                                 _intreturn.reset (new InternalReturn (_session, node));
887                                 processor = _intreturn;
888
889                         } else if (prop->value() == "main-outs") {
890
891                                 if (_main_outs) {
892                                         if (_main_outs->set_state (node, Stateful::loading_state_version)) {
893                                                 return false;
894                                         } else {
895                                                 return true;
896                                         }
897                                 }
898
899                                 _main_outs.reset (new Delivery (_session, _output, _mute_master, node));
900                                 processor = _main_outs;
901
902                         } else {
903                                 error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
904                                 return false;
905                         }
906
907                         if (iter == _processors.end() && processor->display_to_user() && !_processors.empty()) {
908                                 /* check for invisible processors stacked at the end and leave them there */
909                                 ProcessorList::iterator p;
910                                 p = _processors.end();
911                                 --p;
912                                 while (!(*p)->display_to_user() && p != _processors.begin()) {
913                                         --p;
914                                 }
915                                 ++p;
916                                 iter = p;
917                         }
918
919                         return (add_processor (processor, iter) == 0);
920
921                 } else {
922                         error << _("Processor XML node has no type property") << endmsg;
923                         return false;
924                 }
925         }
926
927         catch (failed_constructor &err) {
928                 warning << _("processor could not be created. Ignored.") << endmsg;
929                 return false;
930         }
931 }
932
933
934 bool
935 Route::add_processor_from_xml_2X (const XMLNode& node, int version, ProcessorList::iterator iter)
936 {
937         const XMLProperty *prop;
938
939         try {
940                 boost::shared_ptr<Processor> processor;
941
942                 if (node.name() == "Insert") {
943
944                         if ((prop = node.property ("type")) != 0) {
945
946                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || 
947                                                 prop->value() == "lv2" ||
948                                                 prop->value() == "vst" ||
949                                                 prop->value() == "audiounit") {
950
951                                         processor.reset (new PluginInsert (_session, node));
952
953                                 } else {
954
955                                         processor.reset (new PortInsert (_session, _mute_master, node));
956                                 }
957
958                         }
959
960                 } else if (node.name() == "Send") {
961
962                         processor.reset (new Send (_session, _mute_master, node, version));
963
964                 } else {
965
966                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), node.name()) << endmsg;
967                         return false;
968                 }
969
970                 if (iter == _processors.end() && processor->display_to_user() && !_processors.empty()) {
971                         /* check for invisible processors stacked at the end and leave them there */
972                         ProcessorList::iterator p;
973                         p = _processors.end();
974                         --p;
975                         while (!(*p)->display_to_user() && p != _processors.begin()) {
976                                 --p;
977                         }
978                         ++p;
979                         iter = p;
980                 }
981
982                 return (add_processor (processor, iter) == 0);
983         }
984
985         catch (failed_constructor &err) {
986                 warning << _("processor could not be created. Ignored.") << endmsg;
987                 return false;
988         }
989 }
990
991 int
992 Route::add_processors (const ProcessorList& others, boost::shared_ptr<Processor> before, ProcessorStreams* err)
993 {
994         ProcessorList::iterator loc;
995
996         if (before) {
997                 loc = find(_processors.begin(), _processors.end(), before);
998         } else {
999                 /* nothing specified - at end but before main outs */
1000                 loc = find (_processors.begin(), _processors.end(), _main_outs);
1001         }
1002
1003         return add_processors (others, loc, err);
1004 }
1005
1006 int
1007 Route::add_processors (const ProcessorList& others, ProcessorList::iterator iter, ProcessorStreams* err)
1008 {
1009         /* NOTE: this is intended to be used ONLY when copying
1010            processors from another Route. Hence the subtle
1011            differences between this and ::add_processor()
1012         */
1013
1014         ChanCount old_pms = processor_max_streams;
1015
1016         if (!_session.engine().connected()) {
1017                 return 1;
1018         }
1019
1020         if (others.empty()) {
1021                 return 0;
1022         }
1023
1024         {
1025                 Glib::RWLock::WriterLock lm (_processor_lock);
1026
1027                 ChanCount potential_max_streams = ChanCount::max (_input->n_ports(), _output->n_ports());
1028
1029                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
1030
1031                         // Ensure meter only appears in the list once
1032                         if (*i == _meter) {
1033                                 ProcessorList::iterator m = find(_processors.begin(), _processors.end(), *i);
1034                                 if (m != _processors.end()) {
1035                                         _processors.erase(m);
1036                                 }
1037                         }
1038
1039                         boost::shared_ptr<PluginInsert> pi;
1040
1041                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1042                                 pi->set_count (1);
1043
1044                                 ChanCount m = max (pi->input_streams(), pi->output_streams());
1045
1046                                 if (m > potential_max_streams) {
1047                                         potential_max_streams = m;
1048                                 }
1049                         }
1050
1051                         ProcessorList::iterator inserted = _processors.insert (iter, *i);
1052
1053                         if ((*i)->active()) {
1054                                 (*i)->activate ();
1055                         }
1056
1057                         if (configure_processors_unlocked (err)) {
1058                                 _processors.erase (inserted);
1059                                 configure_processors_unlocked (0); // it worked before we tried to add it ...
1060                                 return -1;
1061                         }
1062
1063                         (*i)->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false, false));
1064                 }
1065
1066                 _output->set_user_latency (0);
1067         }
1068
1069         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1070
1071         return 0;
1072 }
1073
1074 void
1075 Route::placement_range(Placement p, ProcessorList::iterator& start, ProcessorList::iterator& end)
1076 {
1077         if (p == PreFader) {
1078                 start = _processors.begin();
1079                 end = find(_processors.begin(), _processors.end(), _amp);
1080         } else {
1081                 start = find(_processors.begin(), _processors.end(), _amp);
1082                 ++start;
1083                 end = _processors.end();
1084         }
1085 }
1086
1087 /** Turn off all processors with a given placement
1088  * @param p Placement of processors to disable
1089  */
1090 void
1091 Route::disable_processors (Placement p)
1092 {
1093         Glib::RWLock::ReaderLock lm (_processor_lock);
1094
1095         ProcessorList::iterator start, end;
1096         placement_range(p, start, end);
1097
1098         for (ProcessorList::iterator i = start; i != end; ++i) {
1099                 (*i)->deactivate ();
1100         }
1101
1102         _session.set_dirty ();
1103 }
1104
1105 /** Turn off all redirects
1106  */
1107 void
1108 Route::disable_processors ()
1109 {
1110         Glib::RWLock::ReaderLock lm (_processor_lock);
1111
1112         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1113                 (*i)->deactivate ();
1114         }
1115
1116         _session.set_dirty ();
1117 }
1118
1119 /** Turn off all redirects with a given placement
1120  * @param p Placement of redirects to disable
1121  */
1122 void
1123 Route::disable_plugins (Placement p)
1124 {
1125         Glib::RWLock::ReaderLock lm (_processor_lock);
1126
1127         ProcessorList::iterator start, end;
1128         placement_range(p, start, end);
1129
1130         for (ProcessorList::iterator i = start; i != end; ++i) {
1131                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1132                         (*i)->deactivate ();
1133                 }
1134         }
1135
1136         _session.set_dirty ();
1137 }
1138
1139 /** Turn off all plugins
1140  */
1141 void
1142 Route::disable_plugins ()
1143 {
1144         Glib::RWLock::ReaderLock lm (_processor_lock);
1145
1146         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1147                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1148                         (*i)->deactivate ();
1149                 }
1150         }
1151
1152         _session.set_dirty ();
1153 }
1154
1155
1156 void
1157 Route::ab_plugins (bool forward)
1158 {
1159         Glib::RWLock::ReaderLock lm (_processor_lock);
1160
1161         if (forward) {
1162
1163                 /* forward = turn off all active redirects, and mark them so that the next time
1164                    we go the other way, we will revert them
1165                 */
1166
1167                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1168                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1169                                 continue;
1170                         }
1171
1172                         if ((*i)->active()) {
1173                                 (*i)->deactivate ();
1174                                 (*i)->set_next_ab_is_active (true);
1175                         } else {
1176                                 (*i)->set_next_ab_is_active (false);
1177                         }
1178                 }
1179
1180         } else {
1181
1182                 /* backward = if the redirect was marked to go active on the next ab, do so */
1183
1184                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1185
1186                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1187                                 continue;
1188                         }
1189
1190                         if ((*i)->get_next_ab_is_active()) {
1191                                 (*i)->activate ();
1192                         } else {
1193                                 (*i)->deactivate ();
1194                         }
1195                 }
1196         }
1197
1198         _session.set_dirty ();
1199 }
1200
1201
1202 /** Remove processors with a given placement.
1203  * @param p Placement of processors to remove.
1204  */
1205 void
1206 Route::clear_processors (Placement p)
1207 {
1208         const ChanCount old_pms = processor_max_streams;
1209
1210         if (!_session.engine().connected()) {
1211                 return;
1212         }
1213
1214         bool already_deleting = _session.deletion_in_progress();
1215         if (!already_deleting) {
1216                 _session.set_deletion_in_progress();
1217         }
1218
1219         {
1220                 Glib::RWLock::WriterLock lm (_processor_lock);
1221                 ProcessorList new_list;
1222                 ProcessorStreams err;
1223                 bool seen_amp = false;
1224
1225                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1226
1227                         if (*i == _amp) {
1228                                 seen_amp = true;
1229                         }
1230
1231                         if ((*i) == _amp || (*i) == _meter || (*i) == _main_outs) {
1232
1233                                 /* you can't remove these */
1234
1235                                 new_list.push_back (*i);
1236
1237                         } else {
1238                                 if (seen_amp) {
1239
1240                                         switch (p) {
1241                                         case PreFader:
1242                                                 new_list.push_back (*i);
1243                                                 break;
1244                                         case PostFader:
1245                                                 (*i)->drop_references ();
1246                                                 break;
1247                                         }
1248
1249                                 } else {
1250
1251                                         switch (p) {
1252                                         case PreFader:
1253                                                 (*i)->drop_references ();
1254                                                 break;
1255                                         case PostFader:
1256                                                 new_list.push_back (*i);
1257                                                 break;
1258                                         }
1259                                 }
1260                         }
1261                 }
1262
1263                 _processors = new_list;
1264                 configure_processors_unlocked (&err); // this can't fail
1265         }
1266
1267         processor_max_streams.reset();
1268         _have_internal_generator = false;
1269         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1270
1271         if (!already_deleting) {
1272                 _session.clear_deletion_in_progress();
1273         }
1274 }
1275
1276 int
1277 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err)
1278 {
1279         /* these can never be removed */
1280
1281         if (processor == _amp || processor == _meter || processor == _main_outs) {
1282                 return 0;
1283         }
1284
1285         ChanCount old_pms = processor_max_streams;
1286
1287         if (!_session.engine().connected()) {
1288                 return 1;
1289         }
1290
1291         processor_max_streams.reset();
1292
1293         {
1294                 Glib::RWLock::WriterLock lm (_processor_lock);
1295                 ProcessorList::iterator i;
1296                 bool removed = false;
1297
1298                 for (i = _processors.begin(); i != _processors.end(); ) {
1299                         if (*i == processor) {
1300
1301                                 /* move along, see failure case for configure_processors()
1302                                    where we may need to reconfigure the processor.
1303                                 */
1304
1305                                 /* stop redirects that send signals to JACK ports
1306                                    from causing noise as a result of no longer being
1307                                    run.
1308                                 */
1309
1310                                 boost::shared_ptr<IOProcessor> iop;
1311
1312                                 if ((iop = boost::dynamic_pointer_cast<IOProcessor> (*i)) != 0) {
1313                                         if (iop->input()) {
1314                                                 iop->input()->disconnect (this);
1315                                         }
1316                                         if (iop->output()) {
1317                                                 iop->output()->disconnect (this);
1318                                         }
1319                                 }
1320
1321                                 i = _processors.erase (i);
1322                                 removed = true;
1323                                 break;
1324
1325                         } else {
1326                                 ++i;
1327                         }
1328
1329                         _output->set_user_latency (0);
1330                 }
1331
1332                 if (!removed) {
1333                         /* what? */
1334                         return 1;
1335                 }
1336
1337                 if (configure_processors_unlocked (err)) {
1338                         /* get back to where we where */
1339                         _processors.insert (i, processor);
1340                         /* we know this will work, because it worked before :) */
1341                         configure_processors_unlocked (0);
1342                         return -1;
1343                 }
1344
1345                 _have_internal_generator = false;
1346
1347                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1348                         boost::shared_ptr<PluginInsert> pi;
1349
1350                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1351                                 if (pi->is_generator()) {
1352                                         _have_internal_generator = true;
1353                                         break;
1354                                 }
1355                         }
1356                 }
1357         }
1358
1359         processor->drop_references ();
1360         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1361
1362         return 0;
1363 }
1364
1365 int
1366 Route::remove_processors (const ProcessorList& to_be_deleted, ProcessorStreams* err)
1367 {
1368         ProcessorList deleted;
1369         ProcessorList as_we_were;
1370
1371         if (!_session.engine().connected()) {
1372                 return 1;
1373         }
1374
1375         processor_max_streams.reset();
1376
1377         {
1378                 Glib::RWLock::WriterLock lm (_processor_lock);
1379                 ProcessorList::iterator i;
1380                 boost::shared_ptr<Processor> processor;
1381
1382                 as_we_were = _processors;
1383
1384                 for (i = _processors.begin(); i != _processors.end(); ) {
1385
1386                         processor = *i;
1387
1388                         /* these can never be removed */
1389
1390                         if (processor == _amp || processor == _meter || processor == _main_outs) {
1391                                 ++i;
1392                                 continue;
1393                         }
1394
1395                         /* see if its in the list of processors to delete */
1396
1397                         if (find (to_be_deleted.begin(), to_be_deleted.end(), processor) == to_be_deleted.end()) {
1398                                 ++i;
1399                                 continue;
1400                         }
1401
1402                         /* stop IOProcessors that send to JACK ports
1403                            from causing noise as a result of no longer being
1404                            run.
1405                         */
1406
1407                         boost::shared_ptr<IOProcessor> iop;
1408
1409                         if ((iop = boost::dynamic_pointer_cast<IOProcessor> (processor)) != 0) {
1410                                 iop->disconnect ();
1411                         }
1412
1413                         deleted.push_back (processor);
1414                         i = _processors.erase (i);
1415                 }
1416
1417                 if (deleted.empty()) {
1418                         /* none of those in the requested list were found */
1419                         return 0;
1420                 }
1421
1422                 _output->set_user_latency (0);
1423
1424                 if (configure_processors_unlocked (err)) {
1425                         /* get back to where we where */
1426                         _processors = as_we_were;
1427                         /* we know this will work, because it worked before :) */
1428                         configure_processors_unlocked (0);
1429                         return -1;
1430                 }
1431
1432                 _have_internal_generator = false;
1433
1434                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1435                         boost::shared_ptr<PluginInsert> pi;
1436
1437                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1438                                 if (pi->is_generator()) {
1439                                         _have_internal_generator = true;
1440                                         break;
1441                                 }
1442                         }
1443                 }
1444         }
1445
1446         /* now try to do what we need to so that those that were removed will be deleted */
1447
1448         for (ProcessorList::iterator i = deleted.begin(); i != deleted.end(); ++i) {
1449                 (*i)->drop_references ();
1450         }
1451
1452         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1453
1454         return 0;
1455 }
1456
1457
1458 int
1459 Route::configure_processors (ProcessorStreams* err)
1460 {
1461         if (!_in_configure_processors) {
1462                 Glib::RWLock::WriterLock lm (_processor_lock);
1463                 return configure_processors_unlocked (err);
1464         }
1465         return 0;
1466 }
1467
1468 /** Configure the input/output configuration of each processor in the processors list.
1469  * Return 0 on success, otherwise configuration is impossible.
1470  */
1471 int
1472 Route::configure_processors_unlocked (ProcessorStreams* err)
1473 {
1474         if (_in_configure_processors) {
1475            return 0;
1476         }
1477
1478         _in_configure_processors = true;
1479
1480         // Check each processor in order to see if we can configure as requested
1481         ChanCount in = _input->n_ports ();
1482         ChanCount out;
1483         list< pair<ChanCount,ChanCount> > configuration;
1484         uint32_t index = 0;
1485
1486         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configure processors\n", _name));
1487 #ifndef NDEBUG
1488         DEBUG_TRACE (DEBUG::Processors, "{\n");
1489         for (list<boost::shared_ptr<Processor> >::const_iterator p = _processors.begin(); p != _processors.end(); ++p) {
1490                 DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1 ID = %2\n", (*p)->name(), (*p)->id()));
1491         }
1492         DEBUG_TRACE (DEBUG::Processors, "}\n");
1493 #endif
1494
1495         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++index) {
1496
1497                 if ((*p)->can_support_io_configuration(in, out)) {
1498                         DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1in = %2 out = %3\n",(*p)->name(), in, out));
1499                         configuration.push_back(make_pair(in, out));
1500                         in = out;
1501                 } else {
1502                         if (err) {
1503                                 err->index = index;
1504                                 err->count = in;
1505                         }
1506                         _in_configure_processors = false;
1507                         return -1;
1508                 }
1509         }
1510
1511         // We can, so configure everything
1512         list< pair<ChanCount,ChanCount> >::iterator c = configuration.begin();
1513         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++c) {
1514                 (*p)->configure_io(c->first, c->second);
1515                 processor_max_streams = ChanCount::max(processor_max_streams, c->first);
1516                 processor_max_streams = ChanCount::max(processor_max_streams, c->second);
1517                 out = c->second;
1518         }
1519
1520         if (_meter) {
1521                 _meter->reset_max_channels (processor_max_streams);
1522         }
1523
1524         /* make sure we have sufficient scratch buffers to cope with the new processor
1525            configuration */
1526         _session.ensure_buffers (n_process_buffers ());
1527
1528         _in_configure_processors = false;
1529         return 0;
1530 }
1531
1532 void
1533 Route::all_processors_flip ()
1534 {
1535         Glib::RWLock::ReaderLock lm (_processor_lock);
1536
1537         if (_processors.empty()) {
1538                 return;
1539         }
1540
1541         bool first_is_on = _processors.front()->active();
1542
1543         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1544                 if (first_is_on) {
1545                         (*i)->deactivate ();
1546                 } else {
1547                         (*i)->activate ();
1548                 }
1549         }
1550
1551         _session.set_dirty ();
1552 }
1553
1554 /** Set all processors with a given placement to a given active state.
1555  * @param p Placement of processors to change.
1556  * @param state New active state for those processors.
1557  */
1558 void
1559 Route::all_processors_active (Placement p, bool state)
1560 {
1561         Glib::RWLock::ReaderLock lm (_processor_lock);
1562
1563         if (_processors.empty()) {
1564                 return;
1565         }
1566         ProcessorList::iterator start, end;
1567         placement_range(p, start, end);
1568
1569         bool before_amp = true;
1570         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1571                 if ((*i) == _amp) {
1572                         before_amp = false;
1573                         continue;
1574                 }
1575                 if (p == PreFader && before_amp) {
1576                         if (state) {
1577                                 (*i)->activate ();
1578                         } else {
1579                                 (*i)->deactivate ();
1580                         }
1581                 }
1582         }
1583
1584         _session.set_dirty ();
1585 }
1586
1587 bool
1588 Route::processor_is_prefader (boost::shared_ptr<Processor> p)
1589 {
1590         bool pre_fader = true;
1591         Glib::RWLock::ReaderLock lm (_processor_lock);
1592
1593         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1594
1595                 /* semantic note: if p == amp, we want to return true, so test
1596                    for equality before checking if this is the amp
1597                 */
1598
1599                 if ((*i) == p) {
1600                         break;
1601                 }
1602
1603                 if ((*i) == _amp) {
1604                         pre_fader = false;
1605                         break;
1606                 }
1607         }
1608
1609         return pre_fader;
1610 }
1611
1612 int
1613 Route::reorder_processors (const ProcessorList& new_order, ProcessorStreams* err)
1614 {
1615         /* "new_order" is an ordered list of processors to be positioned according to "placement".
1616            NOTE: all processors in "new_order" MUST be marked as display_to_user(). There maybe additional
1617            processors in the current actual processor list that are hidden. Any visible processors
1618            in the current list but not in "new_order" will be assumed to be deleted.
1619         */
1620
1621         {
1622                 Glib::RWLock::WriterLock lm (_processor_lock);
1623                 ChanCount old_pms = processor_max_streams;
1624                 ProcessorList::iterator oiter;
1625                 ProcessorList::const_iterator niter;
1626                 ProcessorList as_it_was_before = _processors;
1627                 ProcessorList as_it_will_be;
1628
1629                 oiter = _processors.begin();
1630                 niter = new_order.begin();
1631
1632                 while (niter !=  new_order.end()) {
1633
1634                         /* if the next processor in the old list is invisible (i.e. should not be in the new order)
1635                            then append it to the temp list.
1636
1637                            Otherwise, see if the next processor in the old list is in the new list. if not,
1638                            its been deleted. If its there, append it to the temp list.
1639                         */
1640
1641                         if (oiter == _processors.end()) {
1642
1643                                 /* no more elements in the old list, so just stick the rest of
1644                                    the new order onto the temp list.
1645                                 */
1646
1647                                 as_it_will_be.insert (as_it_will_be.end(), niter, new_order.end());
1648                                 while (niter != new_order.end()) {
1649                                         ++niter;
1650                                 }
1651                                 break;
1652
1653                         } else {
1654
1655                                 if (!(*oiter)->display_to_user()) {
1656
1657                                         as_it_will_be.push_back (*oiter);
1658
1659                                 } else {
1660
1661                                         /* visible processor: check that its in the new order */
1662
1663                                         if (find (new_order.begin(), new_order.end(), (*oiter)) == new_order.end()) {
1664                                                 /* deleted: do nothing, shared_ptr<> will clean up */
1665                                         } else {
1666                                                 /* ignore this one, and add the next item from the new order instead */
1667                                                 as_it_will_be.push_back (*niter);
1668                                                 ++niter;
1669                                         }
1670                                 }
1671
1672                                 /* now remove from old order - its taken care of no matter what */
1673                                 oiter = _processors.erase (oiter);
1674                         }
1675
1676                 }
1677
1678                 _processors.insert (oiter, as_it_will_be.begin(), as_it_will_be.end());
1679
1680                 if (configure_processors_unlocked (err)) {
1681                         _processors = as_it_was_before;
1682                         processor_max_streams = old_pms;
1683                         return -1;
1684                 }
1685         }
1686
1687         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1688
1689         return 0;
1690 }
1691
1692 XMLNode&
1693 Route::get_state()
1694 {
1695         return state(true);
1696 }
1697
1698 XMLNode&
1699 Route::get_template()
1700 {
1701         return state(false);
1702 }
1703
1704 XMLNode&
1705 Route::state(bool full_state)
1706 {
1707         XMLNode *node = new XMLNode("Route");
1708         ProcessorList::iterator i;
1709         char buf[32];
1710
1711         id().print (buf, sizeof (buf));
1712         node->add_property("id", buf);
1713         node->add_property ("name", _name);
1714         node->add_property("default-type", _default_type.to_string());
1715
1716         if (_flags) {
1717                 node->add_property("flags", enum_2_string (_flags));
1718         }
1719
1720         node->add_property("active", _active?"yes":"no");
1721         node->add_property("phase-invert", _phase_invert?"yes":"no");
1722         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
1723         node->add_property("meter-point", enum_2_string (_meter_point));
1724
1725         if (_route_group) {
1726                 node->add_property("route-group", _route_group->name());
1727         }
1728
1729         string order_string;
1730         OrderKeys::iterator x = order_keys.begin();
1731
1732         while (x != order_keys.end()) {
1733                 order_string += string ((*x).first);
1734                 order_string += '=';
1735                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1736                 order_string += buf;
1737
1738                 ++x;
1739
1740                 if (x == order_keys.end()) {
1741                         break;
1742                 }
1743
1744                 order_string += ':';
1745         }
1746         node->add_property ("order-keys", order_string);
1747         node->add_property ("self-solo", (_self_solo ? "yes" : "no"));
1748         snprintf (buf, sizeof (buf), "%d", _soloed_by_others);
1749         node->add_property ("soloed-by-others", buf);
1750
1751         node->add_child_nocopy (_input->state (full_state));
1752         node->add_child_nocopy (_output->state (full_state));
1753         node->add_child_nocopy (_solo_control->get_state ());
1754         node->add_child_nocopy (_mute_master->get_state ());
1755
1756         XMLNode* remote_control_node = new XMLNode (X_("RemoteControl"));
1757         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1758         remote_control_node->add_property (X_("id"), buf);
1759         node->add_child_nocopy (*remote_control_node);
1760
1761         if (_comment.length()) {
1762                 XMLNode *cmt = node->add_child ("Comment");
1763                 cmt->add_content (_comment);
1764         }
1765
1766         for (i = _processors.begin(); i != _processors.end(); ++i) {
1767                 node->add_child_nocopy((*i)->state (full_state));
1768         }
1769
1770         if (_extra_xml){
1771                 node->add_child_copy (*_extra_xml);
1772         }
1773
1774         return *node;
1775 }
1776
1777 int
1778 Route::set_state (const XMLNode& node, int version)
1779 {
1780         return _set_state (node, version, true);
1781 }
1782
1783 int
1784 Route::_set_state (const XMLNode& node, int version, bool /*call_base*/)
1785 {
1786         if (version < 3000) {
1787                 return _set_state_2X (node, version);
1788         }
1789
1790         XMLNodeList nlist;
1791         XMLNodeConstIterator niter;
1792         XMLNode *child;
1793         XMLPropertyList plist;
1794         const XMLProperty *prop;
1795
1796         if (node.name() != "Route"){
1797                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1798                 return -1;
1799         }
1800
1801         if ((prop = node.property (X_("name"))) != 0) {
1802                 Route::set_name (prop->value());
1803         }
1804
1805         if ((prop = node.property ("id")) != 0) {
1806                 _id = prop->value ();
1807         }
1808
1809         if ((prop = node.property (X_("flags"))) != 0) {
1810                 _flags = Flag (string_2_enum (prop->value(), _flags));
1811         } else {
1812                 _flags = Flag (0);
1813         }
1814
1815         /* add all processors (except amp, which is always present) */
1816
1817         nlist = node.children();
1818         XMLNode processor_state (X_("processor_state"));
1819
1820         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1821
1822                 child = *niter;
1823
1824                 if (child->name() == IO::state_node_name) {
1825                         if ((prop = child->property (X_("direction"))) == 0) {
1826                                 continue;
1827                         }
1828
1829                         if (prop->value() == "Input") {
1830                                 _input->set_state (*child, version);
1831                         } else if (prop->value() == "Output") {
1832                                 _output->set_state (*child, version);
1833                         }
1834                 }
1835
1836                 if (child->name() == X_("Processor")) {
1837                         processor_state.add_child_copy (*child);
1838                 }
1839         }
1840
1841         set_processor_state (processor_state);
1842
1843         if ((prop = node.property ("self-solo")) != 0) {
1844                 set_self_solo (string_is_affirmative (prop->value()));
1845         }
1846
1847         if ((prop = node.property ("soloed-by-others")) != 0) {
1848                 _soloed_by_others = 0; // needed for mod_solo_by_others () to work
1849                 mod_solo_by_others (atoi (prop->value()));
1850         }
1851
1852         if ((prop = node.property ("solo-isolated")) != 0) {
1853                 set_solo_isolated (string_is_affirmative (prop->value()), this);
1854         }
1855
1856         if ((prop = node.property (X_("phase-invert"))) != 0) {
1857                 set_phase_invert (string_is_affirmative (prop->value()));
1858         }
1859
1860         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1861                 set_denormal_protection (string_is_affirmative (prop->value()));
1862         }
1863
1864         if ((prop = node.property (X_("active"))) != 0) {
1865                 bool yn = string_is_affirmative (prop->value());
1866                 _active = !yn; // force switch
1867                 set_active (yn);
1868         }
1869
1870         if ((prop = node.property (X_("meter-point"))) != 0) {
1871                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
1872                 if (_meter) {
1873                         _meter->set_display_to_user (_meter_point == MeterCustom);
1874                 }
1875         }
1876
1877         if ((prop = node.property (X_("order-keys"))) != 0) {
1878
1879                 long n;
1880
1881                 string::size_type colon, equal;
1882                 string remaining = prop->value();
1883
1884                 while (remaining.length()) {
1885
1886                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1887                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1888                                       << endmsg;
1889                         } else {
1890                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1891                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1892                                               << endmsg;
1893                                 } else {
1894                                         set_order_key (remaining.substr (0, equal), n);
1895                                 }
1896                         }
1897
1898                         colon = remaining.find_first_of (':');
1899
1900                         if (colon != string::npos) {
1901                                 remaining = remaining.substr (colon+1);
1902                         } else {
1903                                 break;
1904                         }
1905                 }
1906         }
1907
1908         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1909                 child = *niter;
1910
1911                 if (child->name() == X_("Comment")) {
1912
1913                         /* XXX this is a terrible API design in libxml++ */
1914
1915                         XMLNode *cmt = *(child->children().begin());
1916                         _comment = cmt->content();
1917
1918                 } else if (child->name() == X_("Extra")) {
1919
1920                         _extra_xml = new XMLNode (*child);
1921
1922                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
1923
1924                         if (prop->value() == "solo") {
1925                                 _solo_control->set_state (*child, version);
1926                                 _session.add_controllable (_solo_control);
1927                         }
1928
1929                 } else if (child->name() == X_("RemoteControl")) {
1930                         if ((prop = child->property (X_("id"))) != 0) {
1931                                 int32_t x;
1932                                 sscanf (prop->value().c_str(), "%d", &x);
1933                                 set_remote_control_id (x);
1934                         }
1935
1936                 } else if (child->name() == X_("MuteMaster")) {
1937                         _mute_master->set_state (*child, version);
1938                 }
1939         }
1940
1941         return 0;
1942 }
1943
1944 int
1945 Route::_set_state_2X (const XMLNode& node, int version)
1946 {
1947         XMLNodeList nlist;
1948         XMLNodeConstIterator niter;
1949         XMLNode *child;
1950         XMLPropertyList plist;
1951         const XMLProperty *prop;
1952
1953         /* 2X things which still remain to be handled:
1954          * default-type
1955          * muted
1956          * mute-affects-pre-fader
1957          * mute-affects-post-fader
1958          * mute-affects-control-outs
1959          * mute-affects-main-outs
1960          * automation
1961          * controlouts
1962          */
1963
1964         if (node.name() != "Route") {
1965                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1966                 return -1;
1967         }
1968
1969         if ((prop = node.property (X_("flags"))) != 0) {
1970                 _flags = Flag (string_2_enum (prop->value(), _flags));
1971         } else {
1972                 _flags = Flag (0);
1973         }
1974
1975         /* add standard processors */
1976
1977         _meter.reset (new PeakMeter (_session));
1978         add_processor (_meter, PreFader);
1979
1980         if (_flags & ControlOut) {
1981                 /* where we listen to tracks */
1982                 _intreturn.reset (new InternalReturn (_session));
1983                 add_processor (_intreturn, PreFader);
1984         }
1985
1986         _main_outs.reset (new Delivery (_session, _output, _mute_master, _name, Delivery::Main));
1987         add_processor (_main_outs, PostFader);
1988
1989         /* IOs */
1990
1991         nlist = node.children ();
1992         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1993
1994                 child = *niter;
1995
1996                 if (child->name() == IO::state_node_name) {
1997
1998                         /* there is a note in IO::set_state_2X() about why we have to call
1999                            this directly.
2000                            */
2001
2002                         _input->set_state_2X (*child, version, true);
2003                         _output->set_state_2X (*child, version, false);
2004
2005                         if ((prop = child->property (X_("name"))) != 0) {
2006                                 set_name (prop->value ());
2007                         }
2008
2009                         if ((prop = child->property (X_("id"))) != 0) {
2010                                 _id = prop->value ();
2011                         }
2012
2013                         if ((prop = child->property (X_("active"))) != 0) {
2014                                 bool yn = string_is_affirmative (prop->value());
2015                                 _active = !yn; // force switch
2016                                 set_active (yn);
2017                         }
2018                 }
2019
2020                 /* XXX: panners? */
2021         }
2022
2023         if ((prop = node.property (X_("phase-invert"))) != 0) {
2024                 set_phase_invert (string_is_affirmative (prop->value()));
2025         }
2026
2027         if ((prop = node.property (X_("denormal-protection"))) != 0) {
2028                 set_denormal_protection (string_is_affirmative (prop->value()));
2029         }
2030
2031         if ((prop = node.property (X_("soloed"))) != 0) {
2032                 bool yn = string_is_affirmative (prop->value());
2033
2034                 /* XXX force reset of solo status */
2035
2036                 set_solo (yn, this);
2037         }
2038
2039         if ((prop = node.property (X_("meter-point"))) != 0) {
2040                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
2041         }
2042
2043         /* do not carry over edit/mix groups from 2.X because (a) its hard (b) they
2044            don't mean the same thing.
2045         */
2046
2047         if ((prop = node.property (X_("order-keys"))) != 0) {
2048
2049                 long n;
2050
2051                 string::size_type colon, equal;
2052                 string remaining = prop->value();
2053
2054                 while (remaining.length()) {
2055
2056                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
2057                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2058                                         << endmsg;
2059                         } else {
2060                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
2061                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2062                                                 << endmsg;
2063                                 } else {
2064                                         set_order_key (remaining.substr (0, equal), n);
2065                                 }
2066                         }
2067
2068                         colon = remaining.find_first_of (':');
2069
2070                         if (colon != string::npos) {
2071                                 remaining = remaining.substr (colon+1);
2072                         } else {
2073                                 break;
2074                         }
2075                 }
2076         }
2077
2078         XMLNodeList redirect_nodes;
2079
2080         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2081
2082                 child = *niter;
2083
2084                 if (child->name() == X_("Send") || child->name() == X_("Insert")) {
2085                         redirect_nodes.push_back(child);
2086                 }
2087
2088         }
2089
2090         set_processor_state_2X (redirect_nodes, version);
2091
2092         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2093                 child = *niter;
2094
2095                 if (child->name() == X_("Comment")) {
2096
2097                         /* XXX this is a terrible API design in libxml++ */
2098
2099                         XMLNode *cmt = *(child->children().begin());
2100                         _comment = cmt->content();
2101
2102                 } else if (child->name() == X_("Extra")) {
2103
2104                         _extra_xml = new XMLNode (*child);
2105
2106                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
2107
2108                         if (prop->value() == "solo") {
2109                                 _solo_control->set_state (*child, version);
2110                                 _session.add_controllable (_solo_control);
2111                         }
2112
2113                 } else if (child->name() == X_("RemoteControl")) {
2114                         if ((prop = child->property (X_("id"))) != 0) {
2115                                 int32_t x;
2116                                 sscanf (prop->value().c_str(), "%d", &x);
2117                                 set_remote_control_id (x);
2118                         }
2119
2120                 } 
2121         }
2122
2123         return 0;
2124 }
2125
2126 XMLNode&
2127 Route::get_processor_state ()
2128 {
2129         XMLNode* root = new XMLNode (X_("redirects"));
2130         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2131                 root->add_child_nocopy ((*i)->state (true));
2132         }
2133
2134         return *root;
2135 }
2136
2137 void
2138 Route::set_processor_state_2X (XMLNodeList const & nList, int version)
2139 {
2140         /* We don't bother removing existing processors not in nList, as this
2141            method will only be called when creating a Route from scratch, not
2142            for undo purposes.  Just put processors in at the appropriate place
2143            in the list.
2144         */
2145
2146         for (XMLNodeConstIterator i = nList.begin(); i != nList.end(); ++i) {
2147                 add_processor_from_xml_2X (**i, version, _processors.begin ());
2148         }
2149 }
2150
2151 void
2152 Route::set_processor_state (const XMLNode& node)
2153 {
2154         const XMLNodeList &nlist = node.children();
2155         XMLNodeConstIterator niter;
2156         ProcessorList::iterator i, o;
2157
2158         // Iterate through existing processors, remove those which are not in the state list
2159
2160         for (i = _processors.begin(); i != _processors.end(); ) {
2161
2162                 /* leave amp alone, always */
2163
2164                 if ((*i) == _amp) {
2165                         ++i;
2166                         continue;
2167                 }
2168
2169                 ProcessorList::iterator tmp = i;
2170                 ++tmp;
2171
2172                 bool processorInStateList = false;
2173
2174                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2175
2176                         XMLProperty* id_prop = (*niter)->property(X_("id"));
2177
2178                         if (id_prop && (*i)->id() == id_prop->value()) {
2179                                 processorInStateList = true;
2180                                 break;
2181                         }
2182                 }
2183
2184                 if (!processorInStateList) {
2185                         remove_processor (*i);
2186                 }
2187
2188                 i = tmp;
2189         }
2190
2191         // Iterate through state list and make sure all processors are on the track and in the correct order,
2192         // set the state of existing processors according to the new state on the same go
2193
2194         i = _processors.begin();
2195
2196         for (niter = nlist.begin(); niter != nlist.end(); ++niter, ++i) {
2197
2198                 XMLProperty* prop = (*niter)->property ("type");
2199
2200                 o = i;
2201
2202                 // Check whether the next processor in the list is the right one,
2203                 // except for "amp" which is always there and may not have the
2204                 // old ID since it is always created anew in every Route
2205
2206                 if (prop->value() != "amp") {
2207                         while (o != _processors.end()) {
2208                                 XMLProperty* id_prop = (*niter)->property(X_("id"));
2209                                 if (id_prop && (*o)->id() == id_prop->value()) {
2210                                         break;
2211                                 }
2212
2213                                 ++o;
2214                         }
2215                 }
2216
2217                 // If the processor (*niter) is not on the route,
2218                 // create it and move it to the correct location
2219
2220                 if (o == _processors.end()) {
2221
2222                         if (add_processor_from_xml (**niter, i)) {
2223                                 --i; // move iterator to the newly inserted processor
2224                         } else {
2225                                 cerr << "Error restoring route: unable to restore processor" << endl;
2226                         }
2227
2228                 } else {
2229
2230                         // Otherwise, the processor already exists; just
2231                         // ensure it is at the location provided in the XML state
2232
2233                         if (i != o) {
2234                                 boost::shared_ptr<Processor> tmp = (*o);
2235                                 _processors.erase (o); // remove the old copy
2236                                 _processors.insert (i, tmp); // insert the processor at the correct location
2237                                 --i; // move iterator to the correct processor
2238                         }
2239
2240                         // and make it (just) so
2241
2242                         (*i)->set_state (**niter, Stateful::current_state_version);
2243                 }
2244         }
2245
2246         /* note: there is no configure_processors() call because we figure that
2247            the XML state represents a working signal route.
2248         */
2249
2250         processors_changed (RouteProcessorChange ());
2251 }
2252
2253 void
2254 Route::curve_reallocate ()
2255 {
2256 //      _gain_automation_curve.finish_resize ();
2257 //      _pan_automation_curve.finish_resize ();
2258 }
2259
2260 void
2261 Route::silence (nframes_t nframes)
2262 {
2263         if (!_silent) {
2264
2265                 _output->silence (nframes);
2266
2267                 {
2268                         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2269
2270                         if (lm.locked()) {
2271                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2272                                         boost::shared_ptr<PluginInsert> pi;
2273
2274                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2275                                                 // skip plugins, they don't need anything when we're not active
2276                                                 continue;
2277                                         }
2278
2279                                         (*i)->silence (nframes);
2280                                 }
2281
2282                                 if (nframes == _session.get_block_size()) {
2283                                         // _silent = true;
2284                                 }
2285                         }
2286                 }
2287
2288         }
2289 }
2290
2291 void
2292 Route::add_internal_return ()
2293 {
2294         if (!_intreturn) {
2295                 _intreturn.reset (new InternalReturn (_session));
2296                 add_processor (_intreturn, PreFader);
2297         }
2298 }
2299
2300 BufferSet*
2301 Route::get_return_buffer () const
2302 {
2303         Glib::RWLock::ReaderLock rm (_processor_lock);
2304
2305         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2306                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2307
2308                 if (d) {
2309                         BufferSet* bs = d->get_buffers ();
2310                         return bs;
2311                 }
2312         }
2313
2314         return 0;
2315 }
2316
2317 void
2318 Route::release_return_buffer () const
2319 {
2320         Glib::RWLock::ReaderLock rm (_processor_lock);
2321
2322         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2323                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2324
2325                 if (d) {
2326                         return d->release_buffers ();
2327                 }
2328         }
2329 }
2330
2331 int
2332 Route::listen_via (boost::shared_ptr<Route> route, Placement placement, bool /*active*/, bool aux)
2333 {
2334         vector<string> ports;
2335         vector<string>::const_iterator i;
2336
2337         {
2338                 Glib::RWLock::ReaderLock rm (_processor_lock);
2339
2340                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
2341
2342                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
2343
2344                         if (d && d->target_route() == route) {
2345
2346                                 /* if the target is the control outs, then make sure
2347                                    we take note of which i-send is doing that.
2348                                 */
2349
2350                                 if (route == _session.control_out()) {
2351                                         _control_outs = boost::dynamic_pointer_cast<Delivery>(d);
2352                                 }
2353
2354                                 /* already listening via the specified IO: do nothing */
2355
2356                                 return 0;
2357                         }
2358                 }
2359         }
2360
2361         boost::shared_ptr<InternalSend> listener;
2362
2363         try {
2364                 listener.reset (new InternalSend (_session, _mute_master, route, (aux ? Delivery::Aux : Delivery::Listen)));
2365
2366         } catch (failed_constructor& err) {
2367                 return -1;
2368         }
2369
2370         if (route == _session.control_out()) {
2371                 _control_outs = listener;
2372         }
2373
2374         add_processor (listener, placement);
2375
2376         return 0;
2377 }
2378
2379 void
2380 Route::drop_listen (boost::shared_ptr<Route> route)
2381 {
2382         ProcessorStreams err;
2383         ProcessorList::iterator tmp;
2384
2385         Glib::RWLock::ReaderLock rl(_processor_lock);
2386         rl.acquire ();
2387
2388   again:
2389         for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ) {
2390
2391                 boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
2392
2393                 if (d && d->target_route() == route) {
2394                         rl.release ();
2395                         remove_processor (*x, &err);
2396                         rl.acquire ();
2397
2398                         /* list could have been demolished while we dropped the lock
2399                            so start over.
2400                         */
2401
2402                         goto again;
2403                 }
2404         }
2405
2406         rl.release ();
2407
2408         if (route == _session.control_out()) {
2409                 _control_outs.reset ();
2410         }
2411 }
2412
2413 void
2414 Route::set_comment (string cmt, void *src)
2415 {
2416         _comment = cmt;
2417         comment_changed (src);
2418         _session.set_dirty ();
2419 }
2420
2421 bool
2422 Route::feeds (boost::shared_ptr<Route> other, bool* only_send)
2423 {
2424         DEBUG_TRACE (DEBUG::Graph, string_compose ("Feeds? %1\n", _name));
2425
2426         if (_output->connected_to (other->input())) {
2427                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\tdirect FEEDS %2\n", other->name()));
2428                 if (only_send) {
2429                         *only_send = false;
2430                 }
2431
2432                 return true;
2433         }
2434
2435         
2436         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); r++) {
2437
2438                 boost::shared_ptr<IOProcessor> iop;
2439
2440                 if ((iop = boost::dynamic_pointer_cast<IOProcessor>(*r)) != 0) {
2441                         if (iop->feeds (other)) {
2442                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does feed %2\n", iop->name(), other->name()));
2443                                 if (only_send) {
2444                                         *only_send = true;
2445                                 }
2446                                 return true;
2447                         } else {
2448                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does NOT feed %2\n", iop->name(), other->name()));
2449                         }
2450                 } else {
2451                         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tPROC %1 is not an IOP\n", (*r)->name()));
2452                 }
2453                         
2454         }
2455
2456         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tdoes NOT feed %1\n", other->name()));
2457         return false;
2458 }
2459
2460 void
2461 Route::handle_transport_stopped (bool /*abort_ignored*/, bool did_locate, bool can_flush_processors)
2462 {
2463         nframes_t now = _session.transport_frame();
2464
2465         {
2466                 Glib::RWLock::ReaderLock lm (_processor_lock);
2467
2468                 if (!did_locate) {
2469                         automation_snapshot (now, true);
2470                 }
2471
2472                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2473
2474                         if (Config->get_plugins_stop_with_transport() && can_flush_processors) {
2475                                 (*i)->deactivate ();
2476                                 (*i)->activate ();
2477                         }
2478
2479                         (*i)->transport_stopped (now);
2480                 }
2481         }
2482
2483         _roll_delay = _initial_delay;
2484 }
2485
2486 void
2487 Route::input_change_handler (IOChange change, void * /*src*/)
2488 {
2489         if ((change & ConfigurationChanged)) {
2490                 configure_processors (0);
2491         }
2492 }
2493
2494 void
2495 Route::output_change_handler (IOChange change, void * /*src*/)
2496 {
2497         if ((change & ConfigurationChanged)) {
2498
2499                 /* XXX resize all listeners to match _main_outs? */
2500
2501                 // configure_processors (0);
2502         }
2503 }
2504
2505 uint32_t
2506 Route::pans_required () const
2507 {
2508         if (n_outputs().n_audio() < 2) {
2509                 return 0;
2510         }
2511
2512         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
2513 }
2514
2515 int
2516 Route::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame,
2517                 bool session_state_changing, bool /*can_record*/, bool /*rec_monitors_input*/)
2518 {
2519         if (n_outputs().n_total() == 0) {
2520                 return 0;
2521         }
2522
2523         if (!_active || n_inputs() == ChanCount::ZERO)  {
2524                 silence (nframes);
2525                 return 0;
2526         }
2527         if (session_state_changing) {
2528                 if (_session.transport_speed() != 0.0f) {
2529                         /* we're rolling but some state is changing (e.g. our diskstream contents)
2530                            so we cannot use them. Be silent till this is over.
2531                            
2532                            XXX note the absurdity of ::no_roll() being called when we ARE rolling!
2533                         */
2534                         silence (nframes);
2535                         return 0;
2536                 }
2537                 /* we're really not rolling, so we're either delivery silence or actually
2538                    monitoring, both of which are safe to do while session_state_changing is true.
2539                 */
2540         }
2541
2542         _amp->apply_gain_automation (false);
2543         passthru (start_frame, end_frame, nframes, 0);
2544
2545         return 0;
2546 }
2547
2548 nframes_t
2549 Route::check_initial_delay (nframes_t nframes, nframes_t& transport_frame)
2550 {
2551         if (_roll_delay > nframes) {
2552
2553                 _roll_delay -= nframes;
2554                 silence (nframes);
2555                 /* transport frame is not legal for caller to use */
2556                 return 0;
2557
2558         } else if (_roll_delay > 0) {
2559
2560                 nframes -= _roll_delay;
2561                 silence (_roll_delay);
2562                 /* we've written _roll_delay of samples into the
2563                    output ports, so make a note of that for
2564                    future reference.
2565                 */
2566                 _main_outs->increment_output_offset (_roll_delay);
2567                 transport_frame += _roll_delay;
2568
2569                 _roll_delay = 0;
2570         }
2571
2572         return nframes;
2573 }
2574
2575 int
2576 Route::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
2577              bool /*can_record*/, bool /*rec_monitors_input*/)
2578 {
2579         {
2580                 // automation snapshot can also be called from the non-rt context
2581                 // and it uses the processor list, so we try to acquire the lock here
2582                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2583
2584                 if (lm.locked()) {
2585                         automation_snapshot (_session.transport_frame(), false);
2586                 }
2587         }
2588
2589         if (n_outputs().n_total() == 0) {
2590                 return 0;
2591         }
2592
2593         if (!_active || n_inputs().n_total() == 0) {
2594                 silence (nframes);
2595                 return 0;
2596         }
2597
2598         nframes_t unused = 0;
2599
2600         if ((nframes = check_initial_delay (nframes, unused)) == 0) {
2601                 return 0;
2602         }
2603
2604         _silent = false;
2605
2606         passthru (start_frame, end_frame, nframes, declick);
2607
2608         return 0;
2609 }
2610
2611 int
2612 Route::silent_roll (nframes_t nframes, sframes_t /*start_frame*/, sframes_t /*end_frame*/,
2613                     bool /*can_record*/, bool /*rec_monitors_input*/)
2614 {
2615         silence (nframes);
2616         return 0;
2617 }
2618
2619 void
2620 Route::toggle_monitor_input ()
2621 {
2622         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end(); ++i) {
2623                 i->ensure_monitor_input( ! i->monitoring_input());
2624         }
2625 }
2626
2627 bool
2628 Route::has_external_redirects () const
2629 {
2630         // FIXME: what about sends? - they don't return a signal back to ardour?
2631
2632         boost::shared_ptr<const PortInsert> pi;
2633
2634         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2635
2636                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2637
2638                         for (PortSet::const_iterator port = pi->output()->ports().begin(); port != pi->output()->ports().end(); ++port) {
2639
2640                                 string port_name = port->name();
2641                                 string client_name = port_name.substr (0, port_name.find(':'));
2642
2643                                 /* only say "yes" if the redirect is actually in use */
2644
2645                                 if (client_name != "ardour" && pi->active()) {
2646                                         return true;
2647                                 }
2648                         }
2649                 }
2650         }
2651
2652         return false;
2653 }
2654
2655 void
2656 Route::flush_processors ()
2657 {
2658         /* XXX shouldn't really try to take this lock, since
2659            this is called from the RT audio thread.
2660         */
2661
2662         Glib::RWLock::ReaderLock lm (_processor_lock);
2663
2664         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2665                 (*i)->deactivate ();
2666                 (*i)->activate ();
2667         }
2668 }
2669
2670 void
2671 Route::set_meter_point (MeterPoint p, void *src)
2672 {
2673         /* CAN BE CALLED FROM PROCESS CONTEXT */
2674
2675         if (_meter_point == p) {
2676                 return;
2677         }
2678
2679         bool meter_was_visible_to_user = _meter->display_to_user ();
2680
2681         {
2682                 Glib::RWLock::WriterLock lm (_processor_lock);
2683         
2684                 if (p != MeterCustom) {
2685                         // Move meter in the processors list to reflect the new position
2686                         ProcessorList::iterator loc = find (_processors.begin(), _processors.end(), _meter);
2687                         _processors.erase(loc);
2688                         switch (p) {
2689                         case MeterInput:
2690                                 loc = _processors.begin();
2691                                 break;
2692                         case MeterPreFader:
2693                                 loc = find (_processors.begin(), _processors.end(), _amp);
2694                                 break;
2695                         case MeterPostFader:
2696                                 loc = _processors.end();
2697                                 break;
2698                         default:
2699                                 break;
2700                         }
2701                         
2702                         ChanCount m_in;
2703                         
2704                         if (loc == _processors.begin()) {
2705                                 m_in = _input->n_ports();
2706                         } else {
2707                                 ProcessorList::iterator before = loc;
2708                                 --before;
2709                                 m_in = (*before)->output_streams ();
2710                         }
2711                         
2712                         _meter->reflect_inputs (m_in);
2713                         
2714                         _processors.insert (loc, _meter);
2715                         
2716                         /* we do not need to reconfigure the processors, because the meter
2717                            (a) is always ready to handle processor_max_streams
2718                            (b) is always an N-in/N-out processor, and thus moving
2719                            it doesn't require any changes to the other processors.
2720                         */
2721                         
2722                         _meter->set_display_to_user (false);
2723                         
2724                 } else {
2725                         
2726                         // just make it visible and let the user move it
2727                         
2728                         _meter->set_display_to_user (true);
2729                 }
2730         }
2731
2732         _meter_point = p;
2733         meter_change (src); /* EMIT SIGNAL */
2734
2735         bool const meter_visibly_changed = (_meter->display_to_user() != meter_was_visible_to_user);
2736         
2737         processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, meter_visibly_changed)); /* EMIT SIGNAL */
2738 }
2739
2740 void
2741 Route::put_control_outs_at (Placement p)
2742 {
2743         if (!_control_outs) {
2744                 return;
2745         }
2746
2747         {
2748                 Glib::RWLock::WriterLock lm (_processor_lock);
2749                 ProcessorList as_it_was (_processors);
2750                 // Move meter in the processors list
2751                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), _control_outs);
2752                 _processors.erase(loc);
2753                 
2754                 switch (p) {
2755                 case PreFader:
2756                         loc = find(_processors.begin(), _processors.end(), _amp);
2757                         if (loc != _processors.begin()) {
2758                                 --loc;
2759                         }
2760                         break;
2761                 case PostFader:
2762                         loc = find(_processors.begin(), _processors.end(), _amp);
2763                         assert (loc != _processors.end());
2764                         loc++;
2765                         break;
2766                 }
2767                 
2768                 _processors.insert(loc, _control_outs);
2769
2770                 if (configure_processors_unlocked (0)) {
2771                         _processors = as_it_was;
2772                         configure_processors_unlocked (0); // it worked before we tried to add it ...
2773                         return;
2774                 }
2775         }
2776
2777         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2778         _session.set_dirty ();
2779 }
2780
2781 nframes_t
2782 Route::update_total_latency ()
2783 {
2784         nframes_t old = _output->effective_latency();
2785         nframes_t own_latency = _output->user_latency();
2786
2787         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2788                 if ((*i)->active ()) {
2789                         own_latency += (*i)->signal_latency ();
2790                 }
2791         }
2792
2793         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: internal redirect latency = %2\n", _name, own_latency));
2794
2795         _output->set_port_latency (own_latency);
2796
2797         if (_output->user_latency() == 0) {
2798
2799                 /* this (virtual) function is used for pure Routes,
2800                    not derived classes like AudioTrack.  this means
2801                    that the data processed here comes from an input
2802                    port, not prerecorded material, and therefore we
2803                    have to take into account any input latency.
2804                 */
2805
2806                 own_latency += _input->signal_latency ();
2807         }
2808
2809         if (old != own_latency) {
2810                 _output->set_latency_delay (own_latency);
2811                 signal_latency_changed (); /* EMIT SIGNAL */
2812         }
2813
2814         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: input latency = %2 total = %3\n", _name, _input->signal_latency(), own_latency));
2815
2816         return _output->effective_latency ();
2817 }
2818
2819 void
2820 Route::set_user_latency (nframes_t nframes)
2821 {
2822         _output->set_user_latency (nframes);
2823         _session.update_latency_compensation (false, false);
2824 }
2825
2826 void
2827 Route::set_latency_delay (nframes_t longest_session_latency)
2828 {
2829         nframes_t old = _initial_delay;
2830
2831         if (_output->effective_latency() < longest_session_latency) {
2832                 _initial_delay = longest_session_latency - _output->effective_latency();
2833         } else {
2834                 _initial_delay = 0;
2835         }
2836
2837         if (_initial_delay != old) {
2838                 initial_delay_changed (); /* EMIT SIGNAL */
2839         }
2840
2841         if (_session.transport_stopped()) {
2842                 _roll_delay = _initial_delay;
2843         }
2844 }
2845
2846 void
2847 Route::automation_snapshot (nframes_t now, bool force)
2848 {
2849         panner()->automation_snapshot (now, force);
2850         
2851         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2852                 (*i)->automation_snapshot (now, force);
2853         }
2854 }
2855
2856 Route::SoloControllable::SoloControllable (std::string name, Route& r)
2857         : AutomationControl (r.session(), Evoral::Parameter (SoloAutomation),
2858                              boost::shared_ptr<AutomationList>(), name)
2859         , route (r)
2860 {
2861         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(SoloAutomation)));
2862         set_list (gl);
2863 }
2864
2865 void
2866 Route::SoloControllable::set_value (float val)
2867 {
2868         bool bval = ((val >= 0.5f) ? true: false);
2869 # if 0
2870         this is how it should be done 
2871
2872         boost::shared_ptr<RouteList> rl (new RouteList);
2873         rl->push_back (route);
2874
2875         if (Config->get_solo_control_is_listen_control()) {
2876                 _session.set_listen (rl, bval);
2877         } else {
2878                 _session.set_solo (rl, bval);
2879         }
2880 #else
2881         route.set_solo (bval, this);
2882 #endif
2883 }
2884
2885 float
2886 Route::SoloControllable::get_value (void) const
2887 {
2888         if (Config->get_solo_control_is_listen_control()) {
2889                 return route.listening() ? 1.0f : 0.0f;
2890         } else {
2891                 return route.self_soloed() ? 1.0f : 0.0f;
2892         }
2893 }
2894
2895 Route::MuteControllable::MuteControllable (std::string name, Route& r)
2896         : AutomationControl (r.session(), Evoral::Parameter (MuteAutomation),
2897                              boost::shared_ptr<AutomationList>(), name)
2898         , route (r)
2899 {
2900         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(MuteAutomation)));
2901         set_list (gl);
2902 }
2903
2904 void
2905 Route::MuteControllable::set_value (float val)
2906 {
2907         bool bval = ((val >= 0.5f) ? true: false);
2908 # if 0
2909         this is how it should be done 
2910
2911         boost::shared_ptr<RouteList> rl (new RouteList);
2912         rl->push_back (route);
2913         _session.set_mute (rl, bval);
2914 #else
2915         route.set_mute (bval, this);
2916 #endif
2917 }
2918
2919 float
2920 Route::MuteControllable::get_value (void) const
2921 {
2922         return route.muted() ? 1.0f : 0.0f;
2923 }
2924
2925 void
2926 Route::set_block_size (nframes_t nframes)
2927 {
2928         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2929                 (*i)->set_block_size (nframes);
2930         }
2931         
2932         _session.ensure_buffers (n_process_buffers ());
2933 }
2934
2935 void
2936 Route::protect_automation ()
2937 {
2938         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
2939                 (*i)->protect_automation();
2940 }
2941
2942 void
2943 Route::set_pending_declick (int declick)
2944 {
2945         if (_declickable) {
2946                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2947                 if (declick) {
2948                         _pending_declick = declick;
2949                 }
2950                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2951         } else {
2952                 _pending_declick = 0;
2953         }
2954
2955 }
2956
2957 /** Shift automation forwards from a particular place, thereby inserting time.
2958  *  Adds undo commands for any shifts that are performed.
2959  *
2960  * @param pos Position to start shifting from.
2961  * @param frames Amount to shift forwards by.
2962  */
2963
2964 void
2965 Route::shift (nframes64_t /*pos*/, nframes64_t /*frames*/)
2966 {
2967 #ifdef THIS_NEEDS_FIXING_FOR_V3
2968
2969         /* gain automation */
2970         XMLNode &before = _gain_control->get_state ();
2971         _gain_control->shift (pos, frames);
2972         XMLNode &after = _gain_control->get_state ();
2973         _session.add_command (new MementoCommand<AutomationList> (_gain_automation_curve, &before, &after));
2974
2975         /* pan automation */
2976         for (std::vector<StreamPanner*>::iterator i = _panner->begin (); i != _panner->end (); ++i) {
2977                 Curve & c = (*i)->automation ();
2978                 XMLNode &before = c.get_state ();
2979                 c.shift (pos, frames);
2980                 XMLNode &after = c.get_state ();
2981                 _session.add_command (new MementoCommand<AutomationList> (c, &before, &after));
2982         }
2983
2984         /* redirect automation */
2985         {
2986                 Glib::RWLock::ReaderLock lm (redirect_lock);
2987                 for (RedirectList::iterator i = _redirects.begin (); i != _redirects.end (); ++i) {
2988
2989                         set<uint32_t> a;
2990                         (*i)->what_has_automation (a);
2991
2992                         for (set<uint32_t>::const_iterator j = a.begin (); j != a.end (); ++j) {
2993                                 AutomationList & al = (*i)->automation_list (*j);
2994                                 XMLNode &before = al.get_state ();
2995                                 al.shift (pos, frames);
2996                                 XMLNode &after = al.get_state ();
2997                                 _session.add_command (new MementoCommand<AutomationList> (al, &before, &after));
2998                         }
2999                 }
3000         }
3001 #endif
3002
3003 }
3004
3005
3006 int
3007 Route::save_as_template (const string& path, const string& name)
3008 {
3009         XMLNode& node (state (false));
3010         XMLTree tree;
3011
3012         IO::set_name_in_state (*node.children().front(), name);
3013
3014         tree.set_root (&node);
3015         return tree.write (path.c_str());
3016 }
3017
3018
3019 bool
3020 Route::set_name (const string& str)
3021 {
3022         bool ret;
3023         string ioproc_name;
3024         string name;
3025
3026         name = Route::ensure_track_or_route_name (str, _session);
3027         SessionObject::set_name (name);
3028
3029         ret = (_input->set_name(name) && _output->set_name(name));
3030
3031         if (ret) {
3032
3033                 Glib::RWLock::ReaderLock lm (_processor_lock);
3034
3035                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3036
3037                         /* rename all I/O processors that have inputs or outputs */
3038
3039                         boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor> (*i);
3040
3041                         if (iop && (iop->output() || iop->input())) {
3042                                 if (!iop->set_name (name)) {
3043                                         ret = false;
3044                                 }
3045                         }
3046                 }
3047
3048         }
3049
3050         return ret;
3051 }
3052
3053 boost::shared_ptr<Send>
3054 Route::internal_send_for (boost::shared_ptr<const Route> target) const
3055 {
3056         Glib::RWLock::ReaderLock lm (_processor_lock);
3057
3058         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3059                 boost::shared_ptr<InternalSend> send;
3060
3061                 if ((send = boost::dynamic_pointer_cast<InternalSend>(*i)) != 0) {
3062                         if (send->target_route() == target) {
3063                                 return send;
3064                         }
3065                 }
3066         }
3067
3068         return boost::shared_ptr<Send>();
3069 }
3070
3071 void
3072 Route::set_phase_invert (bool yn)
3073 {
3074         if (_phase_invert != yn) {
3075                 _phase_invert = 0xffff; // XXX all channels
3076                 phase_invert_changed (); /* EMIT SIGNAL */
3077         }
3078 }
3079
3080 bool
3081 Route::phase_invert () const
3082 {
3083         return _phase_invert != 0;
3084 }
3085
3086 void
3087 Route::set_denormal_protection (bool yn)
3088 {
3089         if (_denormal_protection != yn) {
3090                 _denormal_protection = yn;
3091                 denormal_protection_changed (); /* EMIT SIGNAL */
3092         }
3093 }
3094
3095 bool
3096 Route::denormal_protection () const
3097 {
3098         return _denormal_protection;
3099 }
3100
3101 void
3102 Route::set_active (bool yn)
3103 {
3104         if (_active != yn) {
3105                 _active = yn;
3106                 _input->set_active (yn);
3107                 _output->set_active (yn);
3108                 active_changed (); // EMIT SIGNAL
3109         }
3110 }
3111
3112 void
3113 Route::meter ()
3114 {
3115         Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
3116
3117         assert (_meter);
3118
3119         _meter->meter ();
3120
3121         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3122
3123                 boost::shared_ptr<Send> s;
3124                 boost::shared_ptr<Return> r;
3125
3126                 if ((s = boost::dynamic_pointer_cast<Send> (*i)) != 0) {
3127                         s->meter()->meter();
3128                 } else if ((r = boost::dynamic_pointer_cast<Return> (*i)) != 0) {
3129                         r->meter()->meter ();
3130                 }
3131         }
3132 }
3133
3134 boost::shared_ptr<Panner>
3135 Route::panner() const
3136 {
3137         return _main_outs->panner();
3138 }
3139
3140 boost::shared_ptr<AutomationControl>
3141 Route::gain_control() const
3142 {
3143         return _amp->gain_control();
3144 }
3145
3146 boost::shared_ptr<AutomationControl>
3147 Route::get_control (const Evoral::Parameter& param)
3148 {
3149         /* either we own the control or .... */
3150
3151         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(control (param));
3152
3153         if (!c) {
3154
3155                 /* maybe one of our processors does or ... */
3156
3157                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
3158                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3159                         if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->control (param))) != 0) {
3160                                 break;
3161                         }
3162                 }
3163         }
3164
3165         if (!c) {
3166
3167                 /* nobody does so we'll make a new one */
3168
3169                 c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
3170                 add_control(c);
3171         }
3172
3173         return c;
3174 }
3175
3176 boost::shared_ptr<Processor>
3177 Route::nth_plugin (uint32_t n)
3178 {
3179         Glib::RWLock::ReaderLock lm (_processor_lock);
3180         ProcessorList::iterator i;
3181
3182         for (i = _processors.begin(); i != _processors.end(); ++i) {
3183                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
3184                         if (n-- == 0) {
3185                                 return *i;
3186                         }
3187                 }
3188         }
3189
3190         return boost::shared_ptr<Processor> ();
3191 }
3192
3193 boost::shared_ptr<Processor>
3194 Route::nth_send (uint32_t n)
3195 {
3196         Glib::RWLock::ReaderLock lm (_processor_lock);
3197         ProcessorList::iterator i;
3198
3199         for (i = _processors.begin(); i != _processors.end(); ++i) {
3200                 cerr << "check " << (*i)->name() << endl;
3201                 if (boost::dynamic_pointer_cast<Send> (*i)) {
3202                         if (n-- == 0) {
3203                                 return *i;
3204                         }
3205                 } else {
3206                         cerr << "\tnot a send\n";
3207                 }
3208         }
3209
3210         return boost::shared_ptr<Processor> ();
3211 }