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