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