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