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