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