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