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