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