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