First stage of options rework.
[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 <sigc++/bind.h>
26 #include "pbd/xml++.h"
27 #include "pbd/enumwriter.h"
28 #include "pbd/stacktrace.h"
29 #include "pbd/memento_command.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/dB.h"
41 #include "ardour/ladspa_plugin.h"
42 #include "ardour/meter.h"
43 #include "ardour/mix.h"
44 #include "ardour/panner.h"
45 #include "ardour/plugin_insert.h"
46 #include "ardour/port.h"
47 #include "ardour/port_insert.h"
48 #include "ardour/processor.h"
49 #include "ardour/profile.h"
50 #include "ardour/route.h"
51 #include "ardour/route_group.h"
52 #include "ardour/send.h"
53 #include "ardour/session.h"
54 #include "ardour/timestamps.h"
55 #include "ardour/utils.h"
56
57 #include "i18n.h"
58
59 using namespace std;
60 using namespace ARDOUR;
61 using namespace PBD;
62
63 uint32_t Route::order_key_cnt = 0;
64 sigc::signal<void,const char*> Route::SyncOrderKeys;
65
66 Route::Route (Session& sess, string name, Flag flg,
67               DataType default_type, ChanCount in, ChanCount out)
68         : IO (sess, name, default_type, in, ChanCount::INFINITE, out, ChanCount::INFINITE)
69         , _flags (flg)
70         , _solo_control (new ToggleControllable (X_("solo"), *this, ToggleControllable::SoloControl))
71         , _mute_control (new ToggleControllable (X_("mute"), *this, ToggleControllable::MuteControl))
72 {
73         _configured_inputs = in;
74         _configured_outputs = out;
75         init ();
76
77 }
78
79 Route::Route (Session& sess, const XMLNode& node, DataType default_type)
80         : IO (sess, *node.child ("IO"), default_type)
81         , _solo_control (new ToggleControllable (X_("solo"), *this, ToggleControllable::SoloControl))
82         , _mute_control (new ToggleControllable (X_("mute"), *this, ToggleControllable::MuteControl))
83 {
84         init ();
85         _set_state (node, false);
86 }
87
88 void
89 Route::init ()
90 {
91         processor_max_streams.reset();
92         _muted = false;
93         _soloed = false;
94         _solo_safe = false;
95         _recordable = true;
96         _active = true;
97         _phase_invert = false;
98         _denormal_protection = false;
99         order_keys[strdup (N_("signal"))] = order_key_cnt++;
100         _silent = false;
101         _meter_point = MeterPostFader;
102         _initial_delay = 0;
103         _roll_delay = 0;
104         _own_latency = 0;
105         _user_latency = 0;
106         _have_internal_generator = false;
107         _declickable = false;
108         _pending_declick = true;
109         _remote_control_id = 0;
110         _in_configure_processors = false;
111         
112         _edit_group = 0;
113         _mix_group = 0;
114
115         _mute_affects_pre_fader = Config->get_mute_affects_pre_fader();
116         _mute_affects_post_fader = Config->get_mute_affects_post_fader();
117         _mute_affects_control_outs = Config->get_mute_affects_control_outs();
118         _mute_affects_main_outs = Config->get_mute_affects_main_outs();
119         
120         solo_gain = 1.0;
121         desired_solo_gain = 1.0;
122         mute_gain = 1.0;
123         desired_mute_gain = 1.0;
124
125         input_changed.connect (mem_fun (this, &Route::input_change_handler));
126         output_changed.connect (mem_fun (this, &Route::output_change_handler));
127         
128         /* add standard processors: amp, meter, main outs */
129
130         /* amp & meter belong to IO but need to be added to our processor list */
131
132         _amp->set_sort_key (0);
133         _meter->set_sort_key (1);
134         add_processor (_amp);
135         add_processor (_meter);
136         
137         _main_outs.reset (new Delivery (_session, this, _name, Delivery::Main));
138         ProcessorList::iterator i = _processors.end();
139         add_processor (_main_outs, 0, &i);
140 }
141
142 Route::~Route ()
143 {
144         clear_processors (PreFader);
145         clear_processors (PostFader);
146
147         for (OrderKeys::iterator i = order_keys.begin(); i != order_keys.end(); ++i) {
148                 free ((void*)(i->first));
149         }
150 }
151
152 void
153 Route::set_remote_control_id (uint32_t id)
154 {
155         if (id != _remote_control_id) {
156                 _remote_control_id = id;
157                 RemoteControlIDChanged ();
158         }
159 }
160
161 uint32_t
162 Route::remote_control_id() const
163 {
164         return _remote_control_id;
165 }
166
167 long
168 Route::order_key (const char* name) const
169 {
170         OrderKeys::const_iterator i;
171
172         for (i = order_keys.begin(); i != order_keys.end(); ++i) {
173                 if (!strcmp (name, i->first)) {
174                         return i->second;
175                 }
176         }
177
178         return -1;
179 }
180
181 void
182 Route::set_order_key (const char* name, long n)
183 {
184         order_keys[strdup(name)] = n;
185
186         if (Config->get_sync_all_route_ordering()) {
187                 for (OrderKeys::iterator x = order_keys.begin(); x != order_keys.end(); ++x) {
188                         x->second = n;
189                 }
190         } 
191
192         _session.set_dirty ();
193 }
194
195 void
196 Route::sync_order_keys (const char* base)
197 {
198         if (order_keys.empty()) {
199                 return;
200         }
201
202         OrderKeys::iterator i;
203         uint32_t key;
204
205         if ((i = order_keys.find (base)) == order_keys.end()) {
206                 /* key doesn't exist, use the first existing key (during session initialization) */
207                 i = order_keys.begin();
208                 key = i->second;
209                 ++i;
210         } else {
211                 /* key exists - use it and reset all others (actually, itself included) */
212                 key = i->second;
213                 i = order_keys.begin();
214         }
215
216         for (; i != order_keys.end(); ++i) {
217                 i->second = key;
218         }
219 }
220
221 string
222 Route::ensure_track_or_route_name(string name, Session &session)
223 {
224         string newname = name;
225
226         while (session.route_by_name (newname) != NULL) {
227                 newname = bump_name_once (newname);
228         }
229
230         return newname;
231 }
232
233 void
234 Route::inc_gain (gain_t fraction, void *src)
235 {
236         IO::inc_gain (fraction, src);
237 }
238
239 void
240 Route::set_gain (gain_t val, void *src)
241 {
242         if (src != 0 && _mix_group && src != _mix_group && _mix_group->is_active()) {
243                 
244                 if (_mix_group->is_relative()) {
245                         
246                         gain_t usable_gain = gain();
247                         if (usable_gain < 0.000001f) {
248                                 usable_gain = 0.000001f;
249                         }
250                                                 
251                         gain_t delta = val;
252                         if (delta < 0.000001f) {
253                                 delta = 0.000001f;
254                         }
255
256                         delta -= usable_gain;
257
258                         if (delta == 0.0f)
259                                 return;
260
261                         gain_t factor = delta / usable_gain;
262
263                         if (factor > 0.0f) {
264                                 factor = _mix_group->get_max_factor(factor);
265                                 if (factor == 0.0f) {
266                                         _gain_control->Changed(); /* EMIT SIGNAL */
267                                         return;
268                                 }
269                         } else {
270                                 factor = _mix_group->get_min_factor(factor);
271                                 if (factor == 0.0f) {
272                                         _gain_control->Changed(); /* EMIT SIGNAL */
273                                         return;
274                                 }
275                         }
276                                         
277                         _mix_group->apply (&Route::inc_gain, factor, _mix_group);
278
279                 } else {
280                         
281                         _mix_group->apply (&Route::set_gain, val, _mix_group);
282                 }
283
284                 return;
285         } 
286
287         if (val == gain()) {
288                 return;
289         }
290
291         IO::set_gain (val, src);
292 }
293
294 /** Process this route for one (sub) cycle (process thread)
295  *
296  * @param bufs Scratch buffers to use for the signal path
297  * @param start_frame Initial transport frame 
298  * @param end_frame Final transport frame
299  * @param nframes Number of frames to output (to ports)
300  *
301  * Note that (end_frame - start_frame) may not be equal to nframes when the
302  * transport speed isn't 1.0 (eg varispeed).
303  */
304 void
305 Route::process_output_buffers (BufferSet& bufs,
306                                sframes_t start_frame, sframes_t end_frame, nframes_t nframes,
307                                bool with_processors, int declick)
308 {
309         ProcessorList::iterator i;
310         bool mute_declick_applied = false;
311         gain_t dmg, dsg, dg;
312         bool no_monitor;
313
314         bufs.is_silent(false);
315
316         switch (Config->get_monitoring_model()) {
317         case HardwareMonitoring:
318         case ExternalMonitoring:
319                 no_monitor = true;
320                 break;
321         default:
322                 no_monitor = false;
323         }
324
325         declick = _pending_declick;
326         
327         const bool recording_without_monitoring = no_monitor && record_enabled()
328                         && (!_session.config.get_auto_input() || _session.actively_recording());
329         
330
331         /* -------------------------------------------------------------------------------------------
332            SET UP GAIN (FADER)
333            ----------------------------------------------------------------------------------------- */
334
335         { 
336                 Glib::Mutex::Lock dm (declick_lock, Glib::TRY_LOCK);
337                 
338                 if (dm.locked()) {
339                         dmg = desired_mute_gain;
340                         dsg = desired_solo_gain;
341                         dg = _gain_control->user_float();
342                 } else {
343                         dmg = mute_gain;
344                         dsg = solo_gain;
345                         dg = _gain;
346                 }
347         }
348         
349         // apply gain at the amp if...
350         _amp->apply_gain(
351                         // we're not recording
352                         !(record_enabled() && _session.actively_recording())
353                         // or (we are recording, and) software monitoring is required
354                         || Config->get_monitoring_model() == SoftwareMonitoring);
355         
356         // mute at the amp if...
357         _amp->apply_mute (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_post_fader,
358                           mute_gain, dmg);
359
360         _amp->set_gain (_gain, dg);
361         
362
363         /* -------------------------------------------------------------------------------------------
364            SET UP CONTROL OUTPUTS
365            ----------------------------------------------------------------------------------------- */
366
367         boost::shared_ptr<Delivery> co = _control_outs;
368         if (co) {
369                 // deliver control outputs unless we're ...
370                 bool self_mute = ((dmg == 0 && _mute_affects_control_outs) || // or muted by mute of this track
371                                   !recording_without_monitoring); // or rec-enabled w/o s/w monitoring 
372                 bool other_mute = (dsg == 0); // muted by solo of another track
373                 
374                 co->set_self_mute (self_mute);
375                 co->set_nonself_mute (other_mute);
376         }
377
378         /* -------------------------------------------------------------------------------------------
379            SET UP MAIN OUTPUT STAGE
380            ----------------------------------------------------------------------------------------- */
381
382         bool solo_audible = dsg > 0;
383         bool mute_audible = dmg > 0 || !_mute_affects_main_outs;
384
385         bool silent_anyway = (_gain == 0 && !_amp->apply_gain_automation());
386         bool muted_by_other_solo = (!solo_audible && (Config->get_solo_model() != SoloBus));
387         bool muted_by_self = !mute_audible;
388
389         _main_outs->set_nonself_mute (recording_without_monitoring || muted_by_other_solo || silent_anyway);
390         _main_outs->set_self_mute (muted_by_self);
391         
392         /* -------------------------------------------------------------------------------------------
393            GLOBAL DECLICK (for transport changes etc.)
394            ----------------------------------------------------------------------------------------- */
395
396         if (declick > 0) {
397                 Amp::apply_gain (bufs, nframes, 0.0, 1.0, false);
398                 _pending_declick = 0;
399         } else if (declick < 0) {
400                 Amp::apply_gain (bufs, nframes, 1.0, 0.0, false);
401                 _pending_declick = 0;
402         } else { // no global declick
403                 if (solo_gain != dsg) {
404                         Amp::apply_gain (bufs, nframes, solo_gain, dsg, false);
405                         solo_gain = dsg;
406                 }
407         }
408
409
410         /* -------------------------------------------------------------------------------------------
411            PRE-FADER MUTING
412            ----------------------------------------------------------------------------------------- */
413
414         if (!_soloed && _mute_affects_pre_fader && (mute_gain != dmg)) {
415                 Amp::apply_gain (bufs, nframes, mute_gain, dmg, false);
416                 mute_gain = dmg;
417                 mute_declick_applied = true;
418         }
419         if (mute_gain == 0.0f && dmg == 0.0f) {
420                 bufs.is_silent(true);
421         }
422
423
424         /* -------------------------------------------------------------------------------------------
425            DENORMAL CONTROL
426            ----------------------------------------------------------------------------------------- */
427
428         if (_denormal_protection || Config->get_denormal_protection()) {
429
430                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
431                         Sample* const sp = i->data();
432                         
433                         for (nframes_t nx = 0; nx < nframes; ++nx) {
434                                 sp[nx] += 1.0e-27f;
435                         }
436                 }
437         }
438
439         /* -------------------------------------------------------------------------------------------
440            and go ....
441            ----------------------------------------------------------------------------------------- */
442
443         Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
444
445         if (rm.locked()) {
446                 for (i = _processors.begin(); i != _processors.end(); ++i) {
447                         bufs.set_count(ChanCount::max(bufs.count(), (*i)->input_streams()));
448                         (*i)->run_in_place (bufs, start_frame, end_frame, nframes);
449                         bufs.set_count(ChanCount::max(bufs.count(), (*i)->output_streams()));
450                 }
451
452                 if (!_processors.empty()) {
453                         bufs.set_count(ChanCount::max(bufs.count(), _processors.back()->output_streams()));
454                 }
455         }
456
457         /* -------------------------------------------------------------------------------------------
458            POST-FADER MUTING
459            ----------------------------------------------------------------------------------------- */
460
461         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_main_outs) {
462                 Amp::apply_gain (bufs, nframes, mute_gain, dmg, false);
463                 mute_gain = dmg;
464                 mute_declick_applied = true;
465         }
466
467         if (mute_gain == 0.0f && dmg == 0.0f) {
468                 bufs.is_silent(true);
469         }
470         
471         // at this point we've reached the desired mute gain regardless
472         mute_gain = dmg;
473 }
474
475 ChanCount
476 Route::n_process_buffers ()
477 {
478         return max (n_inputs(), processor_max_streams);
479 }
480
481 void
482 Route::setup_peak_meters()
483 {
484         ChanCount max_streams = std::max (_inputs.count(), _outputs.count());
485         max_streams = std::max (max_streams, processor_max_streams);
486         _meter->configure_io (max_streams, max_streams);
487 }
488
489 void
490 Route::passthru (sframes_t start_frame, sframes_t end_frame, nframes_t nframes, int declick)
491 {
492         BufferSet& bufs = _session.get_scratch_buffers(n_process_buffers());
493
494         _silent = false;
495
496         collect_input (bufs, nframes);
497
498         process_output_buffers (bufs, start_frame, end_frame, nframes, true, declick);
499 }
500
501 void
502 Route::passthru_silence (sframes_t start_frame, sframes_t end_frame, nframes_t nframes, int declick)
503 {
504         process_output_buffers (_session.get_silent_buffers (n_process_buffers()), start_frame, end_frame, nframes, true, declick);
505 }
506
507 void
508 Route::set_solo (bool yn, void *src)
509 {
510         if (_solo_safe) {
511                 return;
512         }
513
514         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
515                 _mix_group->apply (&Route::set_solo, yn, _mix_group);
516                 return;
517         }
518
519         if (_soloed != yn) {
520                 _soloed = yn;
521                 solo_changed (src); /* EMIT SIGNAL */
522                 _solo_control->Changed (); /* EMIT SIGNAL */
523         }       
524         
525         catch_up_on_solo_mute_override ();
526 }
527
528 void
529 Route::catch_up_on_solo_mute_override ()
530 {
531         if (Config->get_solo_model() != InverseMute) {
532                 return;
533         }
534         
535         {
536                 Glib::Mutex::Lock lm (declick_lock);
537                 
538                 if (_muted) {
539                         if (Config->get_solo_mute_override()) {
540                                 desired_mute_gain = (_soloed?1.0:0.0);
541                         } else {
542                                 desired_mute_gain = 0.0;
543                         }
544                 } else {
545                         desired_mute_gain = 1.0;
546                 }
547         }
548 }
549
550 void
551 Route::set_solo_mute (bool yn)
552 {
553         Glib::Mutex::Lock lm (declick_lock);
554
555         /* Called by Session in response to another Route being soloed.
556          */
557            
558         desired_solo_gain = (yn?0.0:1.0);
559 }
560
561 void
562 Route::set_solo_safe (bool yn, void *src)
563 {
564         if (_solo_safe != yn) {
565                 _solo_safe = yn;
566                  solo_safe_changed (src); /* EMIT SIGNAL */
567         }
568 }
569
570 void
571 Route::set_mute (bool yn, void *src)
572
573 {
574         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
575                 _mix_group->apply (&Route::set_mute, yn, _mix_group);
576                 return;
577         }
578
579         if (_muted != yn) {
580                 _muted = yn;
581                 mute_changed (src); /* EMIT SIGNAL */
582                 
583                 _mute_control->Changed (); /* EMIT SIGNAL */
584                 
585                 Glib::Mutex::Lock lm (declick_lock);
586                 
587                 if (_soloed && Config->get_solo_mute_override()) {
588                         desired_mute_gain = 1.0f;
589                 } else {
590                         desired_mute_gain = (yn?0.0f:1.0f);
591                 }
592         }
593 }
594
595 static void
596 dump_processors(const string& name, const list<boost::shared_ptr<Processor> >& procs)
597 {
598         cerr << name << " {" << endl;
599         for (list<boost::shared_ptr<Processor> >::const_iterator p = procs.begin();
600                         p != procs.end(); ++p) {
601                 cerr << "\t" << (*p)->sort_key() << ": " << (*p)->name() << endl;
602         }
603         cerr << "}" << endl;
604 }
605
606
607 struct ProcessorSortByKey {
608     bool operator() (boost::shared_ptr<Processor> a, boost::shared_ptr<Processor> b) {
609             return a->sort_key() < b->sort_key();
610     }
611 };
612
613 uint32_t
614 Route::fader_sort_key() const
615 {
616         return _amp->sort_key();
617 }
618
619 /** Add a processor to the route.
620  * If @a iter is not NULL, it must point to an iterator in _processors and the new
621  * processor will be inserted immediately before this location.  Otherwise,
622  * @a position is used.
623  */
624 int
625 Route::add_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err, ProcessorList::iterator* iter)
626 {
627         ChanCount old_pms = processor_max_streams;
628
629         if (!_session.engine().connected() || !processor) {
630                 return 1;
631         }
632
633         cerr << "Adding a processor called " << processor->name() << " sk = " << processor->sort_key() 
634              << ((iter == 0) ? " NO given position " : " with given position")
635              << endl;
636
637         {
638                 Glib::RWLock::WriterLock lm (_processor_lock);
639
640                 boost::shared_ptr<PluginInsert> pi;
641                 boost::shared_ptr<PortInsert> porti;
642
643                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), processor);
644
645                 if (processor == _amp || processor == _meter || processor == _main_outs) {
646                         // Ensure only one of these are in the list at any time
647                         if (loc != _processors.end()) {
648                                 if (iter) {
649                                         if (*iter == loc) { // Already in place, do nothing
650                                                 return 0;
651                                         } else { // New position given, relocate
652                                                 _processors.erase(loc);
653                                         }
654                                 } else { // Insert at end
655                                         _processors.erase(loc);
656                                         loc = _processors.end();
657                                 }
658                         }
659
660                 } else {
661                         if (loc != _processors.end()) {
662                                 cerr << "ERROR: Processor added to route twice!" << endl;
663                                 return 1;
664                         }
665                 }
666
667                 if (iter) {
668                         // Use position given by user
669                         loc = *iter;
670                 } else {
671                         if (processor->sort_key() == 0) {
672                                 /* generic pre-fader: insert immediately before the amp */
673                                 loc = find(_processors.begin(), _processors.end(), _amp);
674                         } else if (processor->sort_key() > _processors.size()) {
675                                 /* generic post-fader: insert at end */
676                                 loc = _processors.end();
677                         } else {
678                                 /* find insert point */
679                                 ProcessorSortByKey cmp;
680                                 loc = upper_bound (_processors.begin(), _processors.end(), processor, cmp);
681                         }
682                 }
683                 
684                 // Update sort keys
685                 if (loc == _processors.end()) {
686                         processor->set_sort_key(_processors.size());
687                 } else {
688                         processor->set_sort_key((*loc)->sort_key());
689                         for (ProcessorList::iterator p = loc; p != _processors.end(); ++p) {
690                                 (*p)->set_sort_key((*p)->sort_key() + 1);
691                         }
692                 }
693
694                 _processors.insert(loc, processor);
695
696                 // Set up processor list channels.  This will set processor->[input|output]_streams(),
697                 // configure redirect ports properly, etc.
698                 if (configure_processors_unlocked (err)) {
699                         dump_processors(_name + "bad config", _processors);
700                         ProcessorList::iterator ploc = loc;
701                         --ploc;
702                         _processors.erase(ploc);
703                         configure_processors_unlocked (0); // it worked before we tried to add it ...
704                         cerr << "Bad IO config\n";
705                         return -1;
706                 }
707         
708                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(processor)) != 0) {
709                         
710                         if (pi->natural_input_streams() == ChanCount::ZERO) {
711                                 /* generator plugin */
712                                 _have_internal_generator = true;
713                         }
714                         
715                 }
716                 
717                 // Ensure peak vector sizes before the plugin is activated
718                 ChanCount potential_max_streams = ChanCount::max (processor->input_streams(), processor->output_streams());
719
720                 _meter->configure_io (potential_max_streams, potential_max_streams);
721
722                 // XXX: do we want to emit the signal here ? change call order.
723                 processor->activate ();
724                 processor->ActiveChanged.connect (bind (mem_fun (_session, &Session::update_latency_compensation), false, false));
725
726                 _user_latency = 0;
727         }
728         
729         if (processor_max_streams != old_pms || old_pms == ChanCount::ZERO) {
730                 reset_panner ();
731         }
732
733         dump_processors (_name + " added one", _processors);
734         processors_changed (); /* EMIT SIGNAL */
735         
736         return 0;
737 }
738
739 int
740 Route::add_processors (const ProcessorList& others, ProcessorStreams* err, uint32_t first_sort_key)
741 {
742         /* NOTE: this is intended to be used ONLY when copying
743            processors from another Route. Hence the subtle
744            differences between this and ::add_processor()
745         */
746
747         ChanCount old_pms = processor_max_streams;
748
749         if (!_session.engine().connected()) {
750                 return 1;
751         }
752
753         {
754                 Glib::RWLock::WriterLock lm (_processor_lock);
755
756                 ProcessorList::iterator loc;
757                 ProcessorList::iterator existing_end = _processors.end();
758                 --existing_end;
759
760                 ChanCount potential_max_streams = ChanCount::max(input_minimum(), output_minimum());
761                 
762                 if (first_sort_key == 0) {
763                         /* generic pre-fader: insert immediately before the amp */
764                         cerr << "Add new procs at amp, sk = " << first_sort_key << endl;
765                         loc = find(_processors.begin(), _processors.end(), _amp);
766                 } else if (first_sort_key > _processors.size()) {
767                         /* generic post-fader: insert at end */
768                         cerr << "Add new procs at end, sk = " << first_sort_key << endl;
769                         loc = _processors.end();
770                 } else {
771                         /* find insert point */
772                         ProcessorSortByKey cmp;
773                         cerr << "Add new procs at sk = " << first_sort_key << endl;
774                         loc = upper_bound (_processors.begin(), _processors.end(), others.front(), cmp);
775                 }
776
777                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
778                         
779                         // Ensure meter only appears in the list once
780                         if (*i == _meter) {
781                                 ProcessorList::iterator m = find(_processors.begin(), _processors.end(), *i);
782                                 if (m != _processors.end()) {
783                                         _processors.erase(m);
784                                 }
785                         }
786                         
787                         boost::shared_ptr<PluginInsert> pi;
788                         
789                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
790                                 pi->set_count (1);
791                                 
792                                 ChanCount m = max(pi->input_streams(), pi->output_streams());
793                                 if (m > potential_max_streams)
794                                         potential_max_streams = m;
795                         }
796
797                         // Ensure peak vector sizes before the plugin is activated
798                         _meter->configure_io (potential_max_streams, potential_max_streams);
799                         
800                         _processors.insert (loc, *i);
801                         
802                         if (configure_processors_unlocked (err)) {
803                                 ++existing_end;
804                                 _processors.erase (existing_end, _processors.end());
805                                 configure_processors_unlocked (0); // it worked before we tried to add it ...
806                                 return -1;
807                         }
808                         
809                         (*i)->ActiveChanged.connect (bind (mem_fun (_session, &Session::update_latency_compensation), false, false));
810                 }
811
812                 _user_latency = 0;
813         }
814         
815         if (processor_max_streams != old_pms || old_pms == ChanCount::ZERO) {
816                 reset_panner ();
817         }
818         
819         dump_processors (_name + " added several", _processors);
820         processors_changed (); /* EMIT SIGNAL */
821
822         return 0;
823 }
824
825 void
826 Route::placement_range(Placement p, ProcessorList::iterator& start, ProcessorList::iterator& end)
827 {
828         if (p == PreFader) {
829                 start = _processors.begin();
830                 end = find(_processors.begin(), _processors.end(), _amp);
831         } else {
832                 start = find(_processors.begin(), _processors.end(), _amp);
833                 ++start;
834                 end = _processors.end();
835         }
836 }
837
838 /** Turn off all processors with a given placement
839  * @param p Placement of processors to disable
840  */
841 void
842 Route::disable_processors (Placement p)
843 {
844         Glib::RWLock::ReaderLock lm (_processor_lock);
845         
846         ProcessorList::iterator start, end;
847         placement_range(p, start, end);
848         
849         for (ProcessorList::iterator i = start; i != end; ++i) {
850                 (*i)->deactivate ();
851         }
852
853         _session.set_dirty ();
854 }
855
856 /** Turn off all redirects 
857  */
858 void
859 Route::disable_processors ()
860 {
861         Glib::RWLock::ReaderLock lm (_processor_lock);
862         
863         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
864                 (*i)->deactivate ();
865         }
866         
867         _session.set_dirty ();
868 }
869
870 /** Turn off all redirects with a given placement
871  * @param p Placement of redirects to disable
872  */
873 void
874 Route::disable_plugins (Placement p)
875 {
876         Glib::RWLock::ReaderLock lm (_processor_lock);
877         
878         ProcessorList::iterator start, end;
879         placement_range(p, start, end);
880         
881         for (ProcessorList::iterator i = start; i != end; ++i) {
882                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
883                         (*i)->deactivate ();
884                 }
885         }
886         
887         _session.set_dirty ();
888 }
889
890 /** Turn off all plugins
891  */
892 void
893 Route::disable_plugins ()
894 {
895         Glib::RWLock::ReaderLock lm (_processor_lock);
896         
897         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
898                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
899                         (*i)->deactivate ();
900                 }
901         }
902         
903         _session.set_dirty ();
904 }
905
906
907 void
908 Route::ab_plugins (bool forward)
909 {
910         Glib::RWLock::ReaderLock lm (_processor_lock);
911                         
912         if (forward) {
913
914                 /* forward = turn off all active redirects, and mark them so that the next time
915                    we go the other way, we will revert them
916                 */
917
918                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
919                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
920                                 continue;
921                         }
922
923                         if ((*i)->active()) {
924                                 (*i)->deactivate ();
925                                 (*i)->set_next_ab_is_active (true);
926                         } else {
927                                 (*i)->set_next_ab_is_active (false);
928                         }
929                 }
930
931         } else {
932
933                 /* backward = if the redirect was marked to go active on the next ab, do so */
934
935                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
936
937                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
938                                 continue;
939                         }
940
941                         if ((*i)->get_next_ab_is_active()) {
942                                 (*i)->activate ();
943                         } else {
944                                 (*i)->deactivate ();
945                         }
946                 }
947         }
948         
949         _session.set_dirty ();
950 }
951         
952         
953 /* Figure out the streams that will feed into PreFader */
954 ChanCount
955 Route::pre_fader_streams() const
956 {
957         boost::shared_ptr<Processor> processor;
958
959         /* Find the last pre-fader redirect that isn't a send; sends don't affect the number
960          * of streams. */
961         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
962                 if ((*i) == _amp) {
963                         break;
964                 }
965                 if (boost::dynamic_pointer_cast<Send> (*i) == 0) {
966                         processor = *i;
967                 }
968         }
969         
970         if (processor) {
971                 return processor->output_streams();
972         } else {
973                 return n_inputs ();
974         }
975 }
976
977
978 /** Remove processors with a given placement.
979  * @param p Placement of processors to remove.
980  */
981 void
982 Route::clear_processors (Placement p)
983 {
984         const ChanCount old_pms = processor_max_streams;
985
986         if (!_session.engine().connected()) {
987                 return;
988         }
989         
990         bool already_deleting = _session.deletion_in_progress();
991         if (!already_deleting) {
992                 _session.set_deletion_in_progress();
993         }
994
995         {
996                 Glib::RWLock::WriterLock lm (_processor_lock);
997                 ProcessorList new_list;
998                 ProcessorStreams err;
999
1000                 ProcessorList::iterator amp_loc = find(_processors.begin(), _processors.end(), _amp);
1001                 if (p == PreFader) {
1002                         // Get rid of PreFader processors
1003                         for (ProcessorList::iterator i = _processors.begin(); i != amp_loc; ++i) {
1004                                 (*i)->drop_references ();
1005                         }
1006                         // Keep the rest
1007                         for (ProcessorList::iterator i = amp_loc; i != _processors.end(); ++i) {
1008                                 new_list.push_back (*i);
1009                         }
1010                 } else {
1011                         // Keep PreFader processors
1012                         for (ProcessorList::iterator i = _processors.begin(); i != amp_loc; ++i) {
1013                                 new_list.push_back (*i);
1014                         }
1015                         new_list.push_back (_amp);
1016                         // Get rid of PostFader processors
1017                         for (ProcessorList::iterator i = amp_loc; i != _processors.end(); ++i) {
1018                                 (*i)->drop_references ();
1019                         }
1020                 }
1021
1022                 _processors = new_list;
1023                 configure_processors_unlocked (&err); // this can't fail
1024         }
1025
1026         if (processor_max_streams != old_pms) {
1027                 reset_panner ();
1028         }
1029         
1030         processor_max_streams.reset();
1031         _have_internal_generator = false;
1032         processors_changed (); /* EMIT SIGNAL */
1033
1034         if (!already_deleting) {
1035                 _session.clear_deletion_in_progress();
1036         }
1037 }
1038
1039 int
1040 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err)
1041 {
1042         /* these can never be removed */
1043
1044         if (processor == _amp || processor == _meter || processor == _main_outs) {
1045                 return 0;
1046         }
1047
1048         ChanCount old_pms = processor_max_streams;
1049
1050         if (!_session.engine().connected()) {
1051                 return 1;
1052         }
1053
1054         processor_max_streams.reset();
1055
1056         {
1057                 Glib::RWLock::WriterLock lm (_processor_lock);
1058                 ProcessorList::iterator i;
1059                 bool removed = false;
1060
1061                 for (i = _processors.begin(); i != _processors.end(); ) {
1062                         if (*i == processor) {
1063
1064                                 /* move along, see failure case for configure_processors()
1065                                    where we may need to reprocessor the processor.
1066                                 */
1067
1068                                 /* stop redirects that send signals to JACK ports
1069                                    from causing noise as a result of no longer being
1070                                    run.
1071                                 */
1072
1073                                 boost::shared_ptr<IOProcessor> redirect;
1074                                 
1075                                 if ((redirect = boost::dynamic_pointer_cast<IOProcessor> (*i)) != 0) {
1076                                         redirect->io()->disconnect_inputs (this);
1077                                         redirect->io()->disconnect_outputs (this);
1078                                 }
1079                                 
1080                                 i = _processors.erase (i);
1081                                 removed = true;
1082                                 break;
1083
1084                         } else {
1085                                 ++i;
1086                         }
1087
1088                         _user_latency = 0;
1089                 }
1090
1091                 if (!removed) {
1092                         /* what? */
1093                         return 1;
1094                 }
1095
1096                 if (configure_processors_unlocked (err)) {
1097                         /* get back to where we where */
1098                         _processors.insert (i, processor);
1099                         /* we know this will work, because it worked before :) */
1100                         configure_processors_unlocked (0);
1101                         return -1;
1102                 }
1103
1104                 _have_internal_generator = false;
1105
1106                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1107                         boost::shared_ptr<PluginInsert> pi;
1108                         
1109                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1110                                 if (pi->is_generator()) {
1111                                         _have_internal_generator = true;
1112                                         break;
1113                                 }
1114                         }
1115                 }
1116         }
1117
1118         if (old_pms != processor_max_streams) {
1119                 reset_panner ();
1120         }
1121
1122         processor->drop_references ();
1123         
1124         dump_processors (_name + " removed one", _processors);
1125         processors_changed (); /* EMIT SIGNAL */
1126
1127         return 0;
1128 }
1129
1130 int
1131 Route::configure_processors (ProcessorStreams* err)
1132 {
1133         if (!_in_configure_processors) {
1134                 Glib::RWLock::WriterLock lm (_processor_lock);
1135                 return configure_processors_unlocked (err);
1136         }
1137         return 0;
1138 }
1139
1140 /** Configure the input/output configuration of each processor in the processors list.
1141  * Return 0 on success, otherwise configuration is impossible.
1142  */
1143 int
1144 Route::configure_processors_unlocked (ProcessorStreams* err)
1145 {
1146         if (_in_configure_processors) {
1147            return 0;
1148         }
1149
1150         _in_configure_processors = true;
1151
1152         // Check each processor in order to see if we can configure as requested
1153         ChanCount in = _configured_inputs;
1154         ChanCount out;
1155         list< pair<ChanCount,ChanCount> > configuration;
1156         uint32_t index = 0;
1157         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++index) {
1158                 (*p)->set_sort_key(index);
1159                 if ((*p)->can_support_io_configuration(in, out)) {
1160                         configuration.push_back(make_pair(in, out));
1161                         in = out;
1162                 } else {
1163                         if (err) {
1164                                 err->index = index;
1165                                 err->count = in;
1166                         }
1167                         _in_configure_processors = false;
1168                         return -1;
1169                 }
1170         }
1171         
1172         // We can, so configure everything
1173         list< pair<ChanCount,ChanCount> >::iterator c = configuration.begin();
1174         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++c) {
1175                 (*p)->configure_io(c->first, c->second);
1176                 (*p)->activate();
1177                 processor_max_streams = ChanCount::max(processor_max_streams, c->first);
1178                 processor_max_streams = ChanCount::max(processor_max_streams, c->second);
1179                 out = c->second;
1180         }
1181
1182         // Ensure route outputs match last processor's outputs
1183         if (out != n_outputs()) {
1184                 ensure_io(_configured_inputs, out, false, this);
1185         }
1186
1187         _in_configure_processors = false;
1188         return 0;
1189 }
1190
1191 void
1192 Route::all_processors_flip ()
1193 {
1194         Glib::RWLock::ReaderLock lm (_processor_lock);
1195
1196         if (_processors.empty()) {
1197                 return;
1198         }
1199
1200         bool first_is_on = _processors.front()->active();
1201         
1202         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1203                 if (first_is_on) {
1204                         (*i)->deactivate ();
1205                 } else {
1206                         (*i)->activate ();
1207                 }
1208         }
1209         
1210         _session.set_dirty ();
1211 }
1212
1213 /** Set all processors with a given placement to a given active state.
1214  * @param p Placement of processors to change.
1215  * @param state New active state for those processors.
1216  */
1217 void
1218 Route::all_processors_active (Placement p, bool state)
1219 {
1220         Glib::RWLock::ReaderLock lm (_processor_lock);
1221
1222         if (_processors.empty()) {
1223                 return;
1224         }
1225         ProcessorList::iterator start, end;
1226         placement_range(p, start, end);
1227
1228         bool before_amp = true;
1229         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1230                 if ((*i) == _amp) {
1231                         before_amp = false;
1232                         continue;
1233                 }
1234                 if (p == PreFader && before_amp) {
1235                         if (state) {
1236                                 (*i)->activate ();
1237                         } else {
1238                                 (*i)->deactivate ();
1239                         }
1240                 }
1241         }
1242         
1243         _session.set_dirty ();
1244 }
1245
1246 int
1247 Route::sort_processors (ProcessorStreams* err)
1248 {
1249         {
1250                 ProcessorSortByKey comparator;
1251                 Glib::RWLock::WriterLock lm (_processor_lock);
1252                 ChanCount old_pms = processor_max_streams;
1253
1254                 /* the sweet power of C++ ... */
1255
1256                 ProcessorList as_it_was_before = _processors;
1257
1258                 dump_processors (_name + " PRESORT", _processors);
1259
1260                 _processors.sort (comparator);
1261         
1262                 if (configure_processors_unlocked (err)) {
1263                         _processors = as_it_was_before;
1264                         processor_max_streams = old_pms;
1265                         return -1;
1266                 } 
1267         } 
1268
1269         dump_processors (_name + " sorted", _processors);
1270         reset_panner ();
1271         processors_changed (); /* EMIT SIGNAL */
1272
1273         return 0;
1274 }
1275
1276 XMLNode&
1277 Route::get_state()
1278 {
1279         return state(true);
1280 }
1281
1282 XMLNode&
1283 Route::get_template()
1284 {
1285         return state(false);
1286 }
1287
1288 XMLNode&
1289 Route::state(bool full_state)
1290 {
1291         XMLNode *node = new XMLNode("Route");
1292         ProcessorList::iterator i;
1293         char buf[32];
1294
1295         if (_flags) {
1296                 node->add_property("flags", enum_2_string (_flags));
1297         }
1298         
1299         node->add_property("default-type", _default_type.to_string());
1300
1301         node->add_property("active", _active?"yes":"no");
1302         node->add_property("muted", _muted?"yes":"no");
1303         node->add_property("soloed", _soloed?"yes":"no");
1304         node->add_property("phase-invert", _phase_invert?"yes":"no");
1305         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
1306         node->add_property("mute-affects-pre-fader", _mute_affects_pre_fader?"yes":"no"); 
1307         node->add_property("mute-affects-post-fader", _mute_affects_post_fader?"yes":"no"); 
1308         node->add_property("mute-affects-control-outs", _mute_affects_control_outs?"yes":"no"); 
1309         node->add_property("mute-affects-main-outs", _mute_affects_main_outs?"yes":"no");
1310         node->add_property("meter-point", enum_2_string (_meter_point));
1311
1312         if (_edit_group) {
1313                 node->add_property("edit-group", _edit_group->name());
1314         }
1315         if (_mix_group) {
1316                 node->add_property("mix-group", _mix_group->name());
1317         }
1318
1319         string order_string;
1320         OrderKeys::iterator x = order_keys.begin(); 
1321
1322         while (x != order_keys.end()) {
1323                 order_string += string ((*x).first);
1324                 order_string += '=';
1325                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1326                 order_string += buf;
1327                 
1328                 ++x;
1329
1330                 if (x == order_keys.end()) {
1331                         break;
1332                 }
1333
1334                 order_string += ':';
1335         }
1336         node->add_property ("order-keys", order_string);
1337
1338         node->add_child_nocopy (IO::state (full_state));
1339         node->add_child_nocopy (_solo_control->get_state ());
1340         node->add_child_nocopy (_mute_control->get_state ());
1341
1342         XMLNode* remote_control_node = new XMLNode (X_("RemoteControl"));
1343         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1344         remote_control_node->add_property (X_("id"), buf);
1345         node->add_child_nocopy (*remote_control_node);
1346
1347         if (_comment.length()) {
1348                 XMLNode *cmt = node->add_child ("Comment");
1349                 cmt->add_content (_comment);
1350         }
1351
1352         for (i = _processors.begin(); i != _processors.end(); ++i) {
1353                 node->add_child_nocopy((*i)->state (full_state));
1354         }
1355
1356         if (_extra_xml){
1357                 node->add_child_copy (*_extra_xml);
1358         }
1359         
1360         return *node;
1361 }
1362
1363 XMLNode&
1364 Route::get_processor_state ()
1365 {
1366         XMLNode* root = new XMLNode (X_("redirects"));
1367         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1368                 root->add_child_nocopy ((*i)->state (true));
1369         }
1370
1371         return *root;
1372 }
1373
1374 int
1375 Route::set_processor_state (const XMLNode& root)
1376 {
1377         if (root.name() != X_("redirects")) {
1378                 return -1;
1379         }
1380
1381         XMLNodeList nlist;
1382         XMLNodeList nnlist;
1383         XMLNodeConstIterator iter;
1384         XMLNodeConstIterator niter;
1385         Glib::RWLock::ReaderLock lm (_processor_lock);
1386
1387         nlist = root.children();
1388         
1389         for (iter = nlist.begin(); iter != nlist.end(); ++iter){
1390
1391                 /* iter now points to a IOProcessor state node */
1392                 
1393                 nnlist = (*iter)->children ();
1394
1395                 for (niter = nnlist.begin(); niter != nnlist.end(); ++niter) {
1396
1397                         /* find the IO child node, since it contains the ID we need */
1398
1399                         /* XXX OOP encapsulation violation, ugh */
1400
1401                         if ((*niter)->name() == IO::state_node_name) {
1402
1403                                 XMLProperty* prop = (*niter)->property (X_("id"));
1404                                 
1405                                 if (!prop) {
1406                                         warning << _("IOProcessor node has no ID, ignored") << endmsg;
1407                                         break;
1408                                 }
1409
1410                                 ID id = prop->value ();
1411
1412                                 /* now look for a processor with that ID */
1413         
1414                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1415                                         if ((*i)->id() == id) {
1416                                                 (*i)->set_state (**iter);
1417                                                 break;
1418                                         }
1419                                 }
1420                                 
1421                                 break;
1422                                 
1423                         }
1424                 }
1425
1426         }
1427
1428         return 0;
1429 }
1430
1431 void
1432 Route::set_deferred_state ()
1433 {
1434         XMLNodeList nlist;
1435         XMLNodeConstIterator niter;
1436
1437         if (!deferred_state) {
1438                 return;
1439         }
1440
1441         nlist = deferred_state->children();
1442
1443         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1444                 add_processor_from_xml (**niter);
1445         }
1446
1447         delete deferred_state;
1448         deferred_state = 0;
1449 }
1450
1451 bool
1452 Route::add_processor_from_xml (const XMLNode& node, ProcessorList::iterator* iter)
1453 {
1454         const XMLProperty *prop;
1455
1456         // legacy sessions use a different node name for sends
1457         if (node.name() == "Send") {
1458         
1459                 try {
1460                         boost::shared_ptr<Send> send (new Send (_session, node));
1461                         add_processor (send, 0, iter);
1462                         return true;
1463                 } 
1464                 
1465                 catch (failed_constructor &err) {
1466                         error << _("Send construction failed") << endmsg;
1467                         return false;
1468                 }
1469                 
1470         } else if (node.name() == "Processor") {
1471                 
1472                 try {
1473                         if ((prop = node.property ("type")) != 0) {
1474
1475                                 boost::shared_ptr<Processor> processor;
1476                                 bool have_insert = false;
1477
1478                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || 
1479                                     prop->value() == "lv2" ||
1480                                     prop->value() == "vst" ||
1481                                     prop->value() == "audiounit") {
1482                                         
1483                                         processor.reset (new PluginInsert(_session, node));
1484                                         have_insert = true;
1485                                         
1486                                 } else if (prop->value() == "port") {
1487
1488                                         processor.reset (new PortInsert (_session, node));
1489                                 
1490                                 } else if (prop->value() == "send") {
1491
1492                                         processor.reset (new Send (_session, node));
1493                                         have_insert = true;
1494                                 
1495                                 } else if (prop->value() == "meter") {
1496
1497                                         processor = _meter;
1498                                 
1499                                 } else if (prop->value() == "amp") {
1500                                         
1501                                         processor = _amp;
1502                                         
1503                                 } else if (prop->value() == "listen" || prop->value() == "deliver") {
1504
1505                                         /* XXX need to generalize */
1506
1507                                         processor = _control_outs;
1508                                         
1509                                 } else if (prop->value() == "main-outs") {
1510                                         
1511                                         processor = _main_outs;
1512                                         
1513                                 } else {
1514
1515                                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
1516                                 }
1517                                 
1518                                 return (add_processor (processor, 0, iter) == 0);
1519                                 
1520                         } else {
1521                                 error << _("Processor XML node has no type property") << endmsg;
1522                         }
1523                 }
1524
1525                 catch (failed_constructor &err) {
1526                         warning << _("processor could not be created. Ignored.") << endmsg;
1527                         return false;
1528                 }
1529         }
1530         return false;
1531 }
1532
1533 int
1534 Route::set_state (const XMLNode& node)
1535 {
1536         return _set_state (node, true);
1537 }
1538
1539 int
1540 Route::_set_state (const XMLNode& node, bool call_base)
1541 {
1542         XMLNodeList nlist;
1543         XMLNodeConstIterator niter;
1544         XMLNode *child;
1545         XMLPropertyList plist;
1546         const XMLProperty *prop;
1547
1548         if (node.name() != "Route"){
1549                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1550                 return -1;
1551         }
1552
1553         if ((prop = node.property (X_("flags"))) != 0) {
1554                 _flags = Flag (string_2_enum (prop->value(), _flags));
1555         } else {
1556                 _flags = Flag (0);
1557         }
1558         
1559         if ((prop = node.property (X_("default-type"))) != 0) {
1560                 _default_type = DataType(prop->value());
1561                 assert(_default_type != DataType::NIL);
1562         }
1563
1564         if ((prop = node.property (X_("phase-invert"))) != 0) {
1565                 set_phase_invert (prop->value()=="yes"?true:false, this);
1566         }
1567
1568         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1569                 set_denormal_protection (prop->value()=="yes"?true:false, this);
1570         }
1571         
1572         _active = true;
1573         if ((prop = node.property (X_("active"))) != 0) {
1574                 set_active (prop->value() == "yes");
1575         }
1576
1577         if ((prop = node.property (X_("muted"))) != 0) {
1578                 bool yn = prop->value()=="yes"?true:false; 
1579
1580                 /* force reset of mute status */
1581
1582                 _muted = !yn;
1583                 set_mute(yn, this);
1584                 mute_gain = desired_mute_gain;
1585         }
1586
1587         if ((prop = node.property (X_("soloed"))) != 0) {
1588                 bool yn = prop->value()=="yes"?true:false; 
1589
1590                 /* force reset of solo status */
1591
1592                 _soloed = !yn;
1593                 set_solo (yn, this);
1594                 solo_gain = desired_solo_gain;
1595         }
1596
1597         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
1598                 _mute_affects_pre_fader = (prop->value()=="yes")?true:false;
1599         }
1600
1601         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
1602                 _mute_affects_post_fader = (prop->value()=="yes")?true:false;
1603         }
1604
1605         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
1606                 _mute_affects_control_outs = (prop->value()=="yes")?true:false;
1607         }
1608
1609         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
1610                 _mute_affects_main_outs = (prop->value()=="yes")?true:false;
1611         }
1612
1613         if ((prop = node.property (X_("meter-point"))) != 0) {
1614                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
1615         }
1616         
1617         if ((prop = node.property (X_("edit-group"))) != 0) {
1618                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
1619                 if(edit_group == 0) {
1620                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1621                 } else {
1622                         set_edit_group(edit_group, this);
1623                 }
1624         }
1625
1626         if ((prop = node.property (X_("order-keys"))) != 0) {
1627
1628                 long n;
1629
1630                 string::size_type colon, equal;
1631                 string remaining = prop->value();
1632
1633                 while (remaining.length()) {
1634
1635                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1636                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1637                                       << endmsg;
1638                         } else {
1639                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1640                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1641                                               << endmsg;
1642                                 } else {
1643                                         set_order_key (remaining.substr (0, equal).c_str(), n);
1644                                 }
1645                         }
1646
1647                         colon = remaining.find_first_of (':');
1648
1649                         if (colon != string::npos) {
1650                                 remaining = remaining.substr (colon+1);
1651                         } else {
1652                                 break;
1653                         }
1654                 }
1655         }
1656
1657         nlist = node.children();
1658
1659         delete deferred_state;
1660         deferred_state = new XMLNode(X_("deferred state"));
1661
1662         /* set parent class properties before anything else */
1663
1664         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1665
1666                 child = *niter;
1667
1668                 if (child->name() == IO::state_node_name && call_base) {
1669                         IO::set_state (*child);
1670                         break;
1671                 }
1672         }
1673
1674         XMLNodeList processor_nodes;
1675         bool has_meter_processor = false; // legacy sessions don't
1676                         
1677         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1678
1679                 child = *niter;
1680                         
1681                 if (child->name() == X_("Send") || child->name() == X_("Processor")) {
1682                         processor_nodes.push_back(child);
1683                         if ((prop = child->property (X_("type"))) != 0 && prop->value() == "meter")  {
1684                                 has_meter_processor = true;
1685                         }
1686                 }
1687
1688         }
1689
1690         _set_processor_states(processor_nodes);
1691         if (!has_meter_processor) {
1692                 set_meter_point(_meter_point, NULL);
1693         }
1694         processors_changed ();
1695
1696         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1697                 child = *niter;
1698                 // All processors have been applied already
1699
1700                 if (child->name() == X_("Automation")) {
1701                         
1702                         if ((prop = child->property (X_("path"))) != 0)  {
1703                                 load_automation (prop->value());
1704                         }
1705
1706                 } else if (child->name() == X_("ControlOuts")) {
1707
1708                         /* ignore this - deprecated */
1709
1710                 } else if (child->name() == X_("Comment")) {
1711
1712                         /* XXX this is a terrible API design in libxml++ */
1713
1714                         XMLNode *cmt = *(child->children().begin());
1715                         _comment = cmt->content();
1716
1717                 } else if (child->name() == X_("Extra")) {
1718
1719                         _extra_xml = new XMLNode (*child);
1720
1721                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
1722                         
1723                         if (prop->value() == "solo") {
1724                                 _solo_control->set_state (*child);
1725                                 _session.add_controllable (_solo_control);
1726                         } else if (prop->value() == "mute") {
1727                                 _mute_control->set_state (*child);
1728                                 _session.add_controllable (_mute_control);
1729                         }
1730                 } else if (child->name() == X_("RemoteControl")) {
1731                         if ((prop = child->property (X_("id"))) != 0) {
1732                                 int32_t x;
1733                                 sscanf (prop->value().c_str(), "%d", &x);
1734                                 set_remote_control_id (x);
1735                         }
1736                 }
1737         }
1738
1739         if ((prop = node.property (X_("mix-group"))) != 0) {
1740                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
1741                 if (mix_group == 0) {
1742                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1743                 }  else {
1744                         set_mix_group(mix_group, this);
1745                 }
1746         }
1747
1748         return 0;
1749 }
1750
1751 void
1752 Route::_set_processor_states(const XMLNodeList &nlist)
1753 {
1754         XMLNodeConstIterator niter;
1755
1756         ProcessorList::iterator i, o;
1757
1758         // Iterate through existing processors, remove those which are not in the state list
1759         for (i = _processors.begin(); i != _processors.end(); ) {
1760                 ProcessorList::iterator tmp = i;
1761                 ++tmp;
1762
1763                 bool processorInStateList = false;
1764         
1765                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1766
1767                         XMLProperty* id_prop = (*niter)->property(X_("id"));
1768                         if (id_prop && (*i)->id() == id_prop->value()) {
1769                                 processorInStateList = true;
1770                                 break;
1771                         }
1772                 }
1773                 
1774                 if (!processorInStateList) {
1775                         remove_processor (*i);
1776                 }
1777
1778                 i = tmp;
1779         }
1780
1781         // Iterate through state list and make sure all processors are on the track and in the correct order,
1782         // set the state of existing processors according to the new state on the same go
1783         i = _processors.begin();
1784
1785         for (niter = nlist.begin(); niter != nlist.end(); ++niter, ++i) {
1786                 
1787                 XMLProperty* prop = (*niter)->property ("type");
1788                 
1789                 o = i;
1790
1791                 if (prop->value() != "meter" && prop->value() != "amp" && prop->value() != "main-outs") {
1792
1793                         // Check whether the next processor in the list 
1794                         
1795                         while (o != _processors.end()) {
1796                                 XMLProperty* id_prop = (*niter)->property(X_("id"));
1797                                 if (id_prop && (*o)->id() == id_prop->value()) {
1798                                         break;
1799                                 }
1800                                 
1801                                 ++o;
1802                         }
1803                 }
1804
1805                 // If the processor (*niter) is not on the route,
1806                 // create it and move it to the correct location
1807                 if (o == _processors.end()) {
1808
1809                         if (add_processor_from_xml (**niter, &i)) {
1810                                 --i; // move iterator to the newly inserted processor
1811                         } else {
1812                                 cerr << "Error restoring route: unable to restore processor" << endl;
1813                         }
1814
1815                 // Otherwise, the processor already exists; just
1816                 // ensure it is at the location provided in the XML state
1817                 } else {
1818
1819                         if (i != o) {
1820                                 boost::shared_ptr<Processor> tmp = (*o);
1821                                 cerr << "move proc from state\n";
1822                                 _processors.erase (o); // remove the old copy
1823                                 _processors.insert (i, tmp); // insert the processor at the correct location
1824                                 --i; // move iterator to the correct processor
1825                         }
1826
1827                         (*i)->set_state (**niter);
1828                 }
1829         }
1830 }
1831
1832 void
1833 Route::curve_reallocate ()
1834 {
1835 //      _gain_automation_curve.finish_resize ();
1836 //      _pan_automation_curve.finish_resize ();
1837 }
1838
1839 void
1840 Route::silence (nframes_t nframes)
1841 {
1842         if (!_silent) {
1843
1844                 IO::silence (nframes);
1845                 
1846                 { 
1847                         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
1848                         
1849                         if (lm.locked()) {
1850                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1851                                         boost::shared_ptr<PluginInsert> pi;
1852
1853                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
1854                                                 // skip plugins, they don't need anything when we're not active
1855                                                 continue;
1856                                         }
1857                                         
1858                                         (*i)->silence (nframes);
1859                                 }
1860
1861                                 if (nframes == _session.get_block_size()) {
1862                                         // _silent = true;
1863                                 }
1864                         }
1865                 }
1866                 
1867         }
1868 }       
1869
1870 boost::shared_ptr<Delivery>
1871 Route::add_listener (boost::shared_ptr<IO> io, const string& listen_name)
1872 {
1873         string name = _name;
1874         name += '[';
1875         name += listen_name;
1876         name += ']';
1877         
1878         boost::shared_ptr<Delivery> listener (new Delivery (_session, name, Delivery::Listen)); 
1879
1880         /* As an IO, our control outs need as many IO outputs as we have outputs
1881          *   (we track the changes in ::output_change_handler()).
1882          * As a processor, the listener is an identity processor
1883          *   (i.e. it does not modify its input buffers whatsoever)
1884          */
1885
1886         if (listener->io()->ensure_io (ChanCount::ZERO, n_outputs(), true, this)) {
1887                 return boost::shared_ptr<Delivery>();
1888         }
1889         
1890         listener->set_sort_key (_meter->sort_key() + 1);
1891         add_processor (listener, NULL);
1892
1893         return listener;
1894 }
1895
1896 int
1897 Route::listen_via (boost::shared_ptr<IO> io, const string& listen_name)
1898 {
1899         vector<string> ports;
1900         vector<string>::const_iterator i;
1901
1902         {
1903                 Glib::RWLock::ReaderLock rm (_processor_lock);
1904                 
1905                 for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
1906                         boost::shared_ptr<const Delivery> d = boost::dynamic_pointer_cast<const Delivery>(*x);
1907
1908                         if (d && d->io() == io) {
1909                                 /* already listening via the specified IO: do nothing */
1910                                 return 0;
1911                         }
1912                 }
1913         }
1914
1915         uint32_t ni = io->n_inputs().n_total();
1916
1917         for (uint32_t n = 0; n < ni; ++n) {
1918                 ports.push_back (io->input(n)->name());
1919         }
1920
1921         if (ports.empty()) {
1922                 return 0;
1923         }
1924         
1925         boost::shared_ptr<Delivery> listen_point = add_listener (io, listen_name);
1926         
1927         /* XXX hack for now .... until we can generalize listen points */
1928
1929         _control_outs = listen_point;
1930
1931         /* now connect to the named ports */
1932         
1933         ni = listen_point->io()->n_outputs().n_total();
1934         size_t psize = ports.size();
1935
1936         for (size_t n = 0; n < ni; ++n) {
1937                 if (listen_point->io()->connect_output (listen_point->io()->output (n), ports[n % psize], this)) {
1938                         error << string_compose (_("could not connect %1 to %2"),
1939                                                  listen_point->io()->output(n)->name(), ports[n % psize]) << endmsg;
1940                         return -1;
1941                 }
1942         }
1943
1944         
1945         return 0;
1946 }       
1947
1948 void
1949 Route::drop_listen (boost::shared_ptr<IO> io)
1950 {
1951         ProcessorStreams err;
1952         ProcessorList::iterator tmp;
1953
1954         Glib::RWLock::ReaderLock rm (_processor_lock);
1955         
1956         for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ) {
1957                 
1958                 tmp = x;
1959                 ++tmp;
1960                 
1961                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery>(*x);
1962                 
1963                 if (d && d->io() == io) {
1964                         /* already listening via the specified IO: do nothing */
1965                         remove_processor (*x, &err);
1966                         
1967                 } 
1968                 
1969                 x = tmp;
1970         }
1971 }
1972
1973 void
1974 Route::set_edit_group (RouteGroup *eg, void *src)
1975
1976 {
1977         if (eg == _edit_group) {
1978                 return;
1979         }
1980
1981         if (_edit_group) {
1982                 _edit_group->remove (this);
1983         }
1984
1985         if ((_edit_group = eg) != 0) {
1986                 _edit_group->add (this);
1987         }
1988
1989         _session.set_dirty ();
1990         edit_group_changed (src); /* EMIT SIGNAL */
1991 }
1992
1993 void
1994 Route::drop_edit_group (void *src)
1995 {
1996         _edit_group = 0;
1997         _session.set_dirty ();
1998         edit_group_changed (src); /* EMIT SIGNAL */
1999 }
2000
2001 void
2002 Route::set_mix_group (RouteGroup *mg, void *src)
2003
2004 {
2005         if (mg == _mix_group) {
2006                 return;
2007         }
2008
2009         if (_mix_group) {
2010                 _mix_group->remove (this);
2011         }
2012
2013         if ((_mix_group = mg) != 0) {
2014                 _mix_group->add (this);
2015         }
2016
2017         _session.set_dirty ();
2018         mix_group_changed (src); /* EMIT SIGNAL */
2019 }
2020
2021 void
2022 Route::drop_mix_group (void *src)
2023 {
2024         _mix_group = 0;
2025         _session.set_dirty ();
2026         mix_group_changed (src); /* EMIT SIGNAL */
2027 }
2028
2029 void
2030 Route::set_comment (string cmt, void *src)
2031 {
2032         _comment = cmt;
2033         comment_changed (src);
2034         _session.set_dirty ();
2035 }
2036
2037 bool
2038 Route::feeds (boost::shared_ptr<Route> other)
2039 {
2040         uint32_t i, j;
2041
2042         IO& self = *this;
2043         uint32_t no = self.n_outputs().n_total();
2044         uint32_t ni = other->n_inputs ().n_total();
2045
2046         for (i = 0; i < no; ++i) {
2047                 for (j = 0; j < ni; ++j) {
2048                         if (self.output(i)->connected_to (other->input(j)->name())) {
2049                                 return true;
2050                         }
2051                 }
2052         }
2053
2054         /* check IOProcessors which may also interconnect Routes */
2055
2056         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); r++) {
2057
2058                 boost::shared_ptr<IOProcessor> proc = boost::dynamic_pointer_cast<IOProcessor>(*r);
2059                 
2060                 if (!proc) {
2061                         continue;
2062                 }
2063                 
2064                 no = proc->io()->n_outputs().n_total();
2065                 
2066                 for (i = 0; i < no; ++i) {
2067                         for (j = 0; j < ni; ++j) {
2068                                 if (proc->io()->output(i)->connected_to (other->input (j)->name())) {
2069                                         return true;
2070                                 }
2071                         }
2072                 }
2073         }
2074
2075         return false;
2076 }
2077
2078 void
2079 Route::set_mute_config (mute_type t, bool onoff, void *src)
2080 {
2081         switch (t) {
2082         case PRE_FADER:
2083                 _mute_affects_pre_fader = onoff;
2084                 pre_fader_changed(src); /* EMIT SIGNAL */
2085                 break;
2086
2087         case POST_FADER:
2088                 _mute_affects_post_fader = onoff;
2089                 post_fader_changed(src); /* EMIT SIGNAL */
2090                 break;
2091
2092         case CONTROL_OUTS:
2093                 _mute_affects_control_outs = onoff;
2094                 control_outs_changed(src); /* EMIT SIGNAL */
2095                 break;
2096
2097         case MAIN_OUTS:
2098                 _mute_affects_main_outs = onoff;
2099                 main_outs_changed(src); /* EMIT SIGNAL */
2100                 break;
2101         }
2102 }
2103
2104 bool
2105 Route::get_mute_config (mute_type t)
2106 {
2107         bool onoff = false;
2108         
2109         switch (t){
2110         case PRE_FADER:
2111                 onoff = _mute_affects_pre_fader; 
2112                 break;
2113         case POST_FADER:
2114                 onoff = _mute_affects_post_fader;
2115                 break;
2116         case CONTROL_OUTS:
2117                 onoff = _mute_affects_control_outs;
2118                 break;
2119         case MAIN_OUTS:
2120                 onoff = _mute_affects_main_outs;
2121                 break;
2122         }
2123         
2124         return onoff;
2125 }
2126
2127 void
2128 Route::handle_transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_processors)
2129 {
2130         nframes_t now = _session.transport_frame();
2131
2132         {
2133                 Glib::RWLock::ReaderLock lm (_processor_lock);
2134
2135                 if (!did_locate) {
2136                         automation_snapshot (now, true);
2137                 }
2138
2139                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2140                         
2141                         if (Config->get_plugins_stop_with_transport() && can_flush_processors) {
2142                                 (*i)->deactivate ();
2143                                 (*i)->activate ();
2144                         }
2145                         
2146                         (*i)->transport_stopped (now);
2147                 }
2148         }
2149
2150         IO::transport_stopped (now);
2151  
2152         _roll_delay = _initial_delay;
2153 }
2154
2155 void
2156 Route::input_change_handler (IOChange change, void *src)
2157 {
2158         if ((change & ConfigurationChanged)) {
2159                 configure_processors (0);
2160         }
2161 }
2162
2163 void
2164 Route::output_change_handler (IOChange change, void *src)
2165 {
2166         if ((change & ConfigurationChanged)) {
2167                 if (_control_outs) {
2168                         _control_outs->io()->ensure_io (ChanCount::ZERO, n_outputs(), true, this);
2169                 }
2170                 
2171                 configure_processors (0);
2172         }
2173 }
2174
2175 uint32_t
2176 Route::pans_required () const
2177 {
2178         if (n_outputs().n_audio() < 2) {
2179                 return 0;
2180         }
2181         
2182         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
2183 }
2184
2185 int 
2186 Route::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame,  
2187                 bool session_state_changing, bool can_record, bool rec_monitors_input)
2188 {
2189         if (n_outputs().n_total() == 0) {
2190                 return 0;
2191         }
2192
2193         if (session_state_changing || !_active)  {
2194                 silence (nframes);
2195                 return 0;
2196         }
2197
2198         _amp->apply_gain_automation(false);
2199         
2200         if (n_inputs() != ChanCount::ZERO) {
2201                 passthru (start_frame, end_frame, nframes, 0);
2202         } else {
2203                 silence (nframes);
2204         }
2205
2206         return 0;
2207 }
2208
2209 nframes_t
2210 Route::check_initial_delay (nframes_t nframes, nframes_t& transport_frame)
2211 {
2212         if (_roll_delay > nframes) {
2213
2214                 _roll_delay -= nframes;
2215                 silence (nframes);
2216                 /* transport frame is not legal for caller to use */
2217                 return 0;
2218
2219         } else if (_roll_delay > 0) {
2220
2221                 nframes -= _roll_delay;
2222                 silence (_roll_delay);
2223                 /* we've written _roll_delay of samples into the 
2224                    output ports, so make a note of that for
2225                    future reference.
2226                 */
2227                 increment_output_offset (_roll_delay);
2228                 transport_frame += _roll_delay;
2229
2230                 _roll_delay = 0;
2231         }
2232
2233         return nframes;
2234 }
2235
2236 int
2237 Route::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
2238              bool can_record, bool rec_monitors_input)
2239 {
2240         {
2241                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2242                 if (lm.locked()) {
2243                         // automation snapshot can also be called from the non-rt context
2244                         // and it uses the processor list, so we take the lock out here
2245                         automation_snapshot (_session.transport_frame(), false);
2246                 }
2247         }
2248
2249         if ((n_outputs().n_total() == 0 && _processors.empty()) || n_inputs().n_total() == 0 || !_active) {
2250                 silence (nframes);
2251                 return 0;
2252         }
2253         
2254         nframes_t unused = 0;
2255
2256         if ((nframes = check_initial_delay (nframes, unused)) == 0) {
2257                 return 0;
2258         }
2259
2260         _silent = false;
2261
2262         _amp->apply_gain_automation(false);
2263
2264         { 
2265                 Glib::Mutex::Lock am (data().control_lock(), Glib::TRY_LOCK);
2266                 
2267                 if (am.locked() && _session.transport_rolling()) {
2268                         
2269                         if (_gain_control->automation_playback()) {
2270                                 _amp->apply_gain_automation(
2271                                                 _gain_control->list()->curve().rt_safe_get_vector (
2272                                                         start_frame, end_frame, _session.gain_automation_buffer(), nframes));
2273                         }
2274                 }
2275         }
2276
2277         passthru (start_frame, end_frame, nframes, declick);
2278
2279         return 0;
2280 }
2281
2282 int
2283 Route::silent_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, 
2284                     bool can_record, bool rec_monitors_input)
2285 {
2286         silence (nframes);
2287         return 0;
2288 }
2289
2290 void
2291 Route::toggle_monitor_input ()
2292 {
2293         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2294                 i->ensure_monitor_input( ! i->monitoring_input());
2295         }
2296 }
2297
2298 bool
2299 Route::has_external_redirects () const
2300 {
2301         // FIXME: what about sends?
2302
2303         boost::shared_ptr<const PortInsert> pi;
2304         
2305         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2306                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2307
2308                         for (PortSet::const_iterator port = pi->io()->outputs().begin();
2309                                         port != pi->io()->outputs().end(); ++port) {
2310                                 
2311                                 string port_name = port->name();
2312                                 string client_name = port_name.substr (0, port_name.find(':'));
2313
2314                                 /* only say "yes" if the redirect is actually in use */
2315                                 
2316                                 if (client_name != "ardour" && pi->active()) {
2317                                         return true;
2318                                 }
2319                         }
2320                 }
2321         }
2322
2323         return false;
2324 }
2325
2326 void
2327 Route::flush_processors ()
2328 {
2329         /* XXX shouldn't really try to take this lock, since
2330            this is called from the RT audio thread.
2331         */
2332
2333         Glib::RWLock::ReaderLock lm (_processor_lock);
2334
2335         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2336                 (*i)->deactivate ();
2337                 (*i)->activate ();
2338         }
2339 }
2340
2341 void
2342 Route::set_meter_point (MeterPoint p, void *src)
2343 {
2344         if (_meter_point != p) {
2345                 _meter_point = p;
2346
2347                 // Move meter in the processors list
2348                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), _meter);
2349                 _processors.erase(loc);
2350                 switch (p) {
2351                 case MeterInput:
2352                         loc = _processors.begin();
2353                         break;
2354                 case MeterPreFader:
2355                         loc = find(_processors.begin(), _processors.end(), _amp);
2356                         break;
2357                 case MeterPostFader:
2358                         loc = _processors.end();
2359                         break;
2360                 }
2361                 _processors.insert(loc, _meter);
2362                 
2363                 // Update sort key
2364                 if (loc == _processors.end()) {
2365                         _meter->set_sort_key(_processors.size());
2366                 } else {
2367                         _meter->set_sort_key((*loc)->sort_key());
2368                         for (ProcessorList::iterator p = loc; p != _processors.end(); ++p) {
2369                                 (*p)->set_sort_key((*p)->sort_key() + 1);
2370                         }
2371                 }
2372
2373                  meter_change (src); /* EMIT SIGNAL */
2374                 processors_changed (); /* EMIT SIGNAL */
2375                 _session.set_dirty ();
2376         }
2377 }
2378
2379 nframes_t
2380 Route::update_total_latency ()
2381 {
2382         nframes_t old = _own_latency;
2383
2384         if (_user_latency) {
2385                 _own_latency = _user_latency;
2386         } else {
2387                 _own_latency = 0;
2388
2389                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2390                         if ((*i)->active ()) {
2391                                 _own_latency += (*i)->signal_latency ();
2392                         }
2393                 }
2394         }
2395
2396 #undef DEBUG_LATENCY
2397 #ifdef DEBUG_LATENCY
2398         cerr << _name << ": internal redirect latency = " << _own_latency << endl;
2399 #endif
2400
2401         set_port_latency (_own_latency);
2402         
2403         if (!_user_latency) {
2404                 /* this (virtual) function is used for pure Routes,
2405                    not derived classes like AudioTrack.  this means
2406                    that the data processed here comes from an input
2407                    port, not prerecorded material, and therefore we
2408                    have to take into account any input latency.
2409                 */
2410
2411
2412                 _own_latency += input_latency ();
2413         }
2414
2415         if (old != _own_latency) {
2416                 signal_latency_changed (); /* EMIT SIGNAL */
2417         }
2418         
2419 #ifdef DEBUG_LATENCY
2420         cerr << _name << ": input latency = " << input_latency() << " total = "
2421              << _own_latency << endl;
2422 #endif
2423
2424         return _own_latency;
2425 }
2426
2427 void
2428 Route::set_user_latency (nframes_t nframes)
2429 {
2430         Latent::set_user_latency (nframes);
2431         _session.update_latency_compensation (false, false);
2432 }
2433
2434 void
2435 Route::set_latency_delay (nframes_t longest_session_latency)
2436 {
2437         nframes_t old = _initial_delay;
2438
2439         if (_own_latency < longest_session_latency) {
2440                 _initial_delay = longest_session_latency - _own_latency;
2441         } else {
2442                 _initial_delay = 0;
2443         }
2444
2445         if (_initial_delay != old) {
2446                 initial_delay_changed (); /* EMIT SIGNAL */
2447         }
2448
2449         if (_session.transport_stopped()) {
2450                 _roll_delay = _initial_delay;
2451         }
2452 }
2453
2454 void
2455 Route::automation_snapshot (nframes_t now, bool force)
2456 {
2457         if (!force && !should_snapshot(now)) {
2458                 return;
2459         }
2460
2461         IO::automation_snapshot (now, force);
2462
2463         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2464                 (*i)->automation_snapshot (now, force);
2465         }
2466 }
2467
2468 Route::ToggleControllable::ToggleControllable (std::string name, Route& s, ToggleType tp)
2469         : Controllable (name), route (s), type(tp)
2470 {
2471         
2472 }
2473
2474 void
2475 Route::ToggleControllable::set_value (float val)
2476 {
2477         bool bval = ((val >= 0.5f) ? true: false);
2478         
2479         switch (type) {
2480         case MuteControl:
2481                 route.set_mute (bval, this);
2482                 break;
2483         case SoloControl:
2484                 route.set_solo (bval, this);
2485                 break;
2486         default:
2487                 break;
2488         }
2489 }
2490
2491 float
2492 Route::ToggleControllable::get_value (void) const
2493 {
2494         float val = 0.0f;
2495         
2496         switch (type) {
2497         case MuteControl:
2498                 val = route.muted() ? 1.0f : 0.0f;
2499                 break;
2500         case SoloControl:
2501                 val = route.soloed() ? 1.0f : 0.0f;
2502                 break;
2503         default:
2504                 break;
2505         }
2506
2507         return val;
2508 }
2509
2510 void 
2511 Route::set_block_size (nframes_t nframes)
2512 {
2513         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2514                 (*i)->set_block_size (nframes);
2515         }
2516         _session.ensure_buffers(processor_max_streams);
2517 }
2518
2519 void
2520 Route::protect_automation ()
2521 {
2522         Automatable::protect_automation();
2523         
2524         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
2525                 (*i)->protect_automation();
2526 }
2527
2528 void
2529 Route::set_pending_declick (int declick)
2530 {
2531         if (_declickable) {
2532                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2533                 if (declick) {
2534                         _pending_declick = declick;
2535                 }
2536                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2537         } else {
2538                 _pending_declick = 0;
2539         }
2540
2541 }
2542
2543 /** Shift automation forwards from a particular place, thereby inserting time.
2544  *  Adds undo commands for any shifts that are performed.
2545  *
2546  * @param pos Position to start shifting from.
2547  * @param frames Amount to shift forwards by.
2548  */
2549
2550 void
2551 Route::shift (nframes64_t pos, nframes64_t frames)
2552 {
2553 #ifdef THIS_NEEDS_FIXING_FOR_V3
2554
2555         /* gain automation */
2556         XMLNode &before = _gain_control->get_state ();
2557         _gain_control->shift (pos, frames);
2558         XMLNode &after = _gain_control->get_state ();
2559         _session.add_command (new MementoCommand<AutomationList> (_gain_automation_curve, &before, &after));
2560
2561         /* pan automation */
2562         for (std::vector<StreamPanner*>::iterator i = _panner->begin (); i != _panner->end (); ++i) {
2563                 Curve & c = (*i)->automation ();
2564                 XMLNode &before = c.get_state ();
2565                 c.shift (pos, frames);
2566                 XMLNode &after = c.get_state ();
2567                 _session.add_command (new MementoCommand<AutomationList> (c, &before, &after));
2568         }
2569
2570         /* redirect automation */
2571         {
2572                 Glib::RWLock::ReaderLock lm (redirect_lock);
2573                 for (RedirectList::iterator i = _redirects.begin (); i != _redirects.end (); ++i) {
2574                         
2575                         set<uint32_t> a;
2576                         (*i)->what_has_automation (a);
2577                         
2578                         for (set<uint32_t>::const_iterator j = a.begin (); j != a.end (); ++j) {
2579                                 AutomationList & al = (*i)->automation_list (*j);
2580                                 XMLNode &before = al.get_state ();
2581                                 al.shift (pos, frames);
2582                                 XMLNode &after = al.get_state ();
2583                                 _session.add_command (new MementoCommand<AutomationList> (al, &before, &after));
2584                         }
2585                 }
2586         }
2587 #endif
2588
2589 }
2590
2591
2592 int
2593 Route::save_as_template (const string& path, const string& name)
2594 {
2595         XMLNode& node (state (false));
2596         XMLTree tree;
2597         
2598         IO::set_name_in_state (*node.children().front(), name);
2599         
2600         tree.set_root (&node);
2601         return tree.write (path.c_str());
2602 }
2603
2604
2605 bool
2606 Route::set_name (const string& str)
2607 {
2608         bool ret;
2609         string ioproc_name;
2610
2611         if ((ret = IO::set_name (str)) == true) {
2612                 Glib::RWLock::ReaderLock lm (_processor_lock);
2613                 
2614                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2615                         
2616                         /* rename all delivery objects to reflect our new name */
2617
2618                         boost::shared_ptr<Delivery> dp = boost::dynamic_pointer_cast<Delivery> (*i);
2619
2620                         if (dp) {
2621                                 string dp_name = str;
2622                                 dp_name += '[';
2623                                 dp_name += "XXX FIX ME XXX";
2624                                 dp_name += ']';
2625                                 
2626                                 if (!dp->set_name (dp_name)) {
2627                                         ret = false;
2628                                 }
2629                         }
2630                 }
2631
2632         }
2633
2634         return ret;
2635 }