d41574183124ddf5318667a66991b911e1595549
[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     $Id$
19 */
20
21 #include <cmath>
22 #include <fstream>
23 #include <cassert>
24
25 #include <sigc++/bind.h>
26 #include <pbd/xml++.h>
27 #include <pbd/enumwriter.h>
28
29 #include <ardour/timestamps.h>
30 #include <ardour/audioengine.h>
31 #include <ardour/route.h>
32 #include <ardour/buffer.h>
33 #include <ardour/insert.h>
34 #include <ardour/send.h>
35 #include <ardour/session.h>
36 #include <ardour/utils.h>
37 #include <ardour/configuration.h>
38 #include <ardour/cycle_timer.h>
39 #include <ardour/route_group.h>
40 #include <ardour/port.h>
41 #include <ardour/audio_port.h>
42 #include <ardour/ladspa_plugin.h>
43 #include <ardour/panner.h>
44 #include <ardour/dB.h>
45 #include <ardour/mix.h>
46 #include <ardour/amp.h>
47 #include <ardour/meter.h>
48 #include <ardour/buffer_set.h>
49 #include "i18n.h"
50
51 using namespace std;
52 using namespace ARDOUR;
53 using namespace PBD;
54
55 uint32_t Route::order_key_cnt = 0;
56
57
58 Route::Route (Session& sess, string name, int input_min, int input_max, int output_min, int output_max, Flag flg, DataType default_type)
59         : IO (sess, name, input_min, input_max, output_min, output_max, default_type),
60           _flags (flg),
61           _solo_control (X_("solo"), *this, ToggleControllable::SoloControl),
62           _mute_control (X_("mute"), *this, ToggleControllable::MuteControl)
63 {
64         init ();
65 }
66
67 Route::Route (Session& sess, const XMLNode& node, DataType default_type)
68         : IO (sess, *node.child ("IO"), default_type),
69           _solo_control (X_("solo"), *this, ToggleControllable::SoloControl),
70           _mute_control (X_("mute"), *this, ToggleControllable::MuteControl)
71 {
72         init ();
73         _set_state (node, false);
74 }
75
76 void
77 Route::init ()
78 {
79         redirect_max_outs.reset();
80         _muted = false;
81         _soloed = false;
82         _solo_safe = false;
83         _phase_invert = false;
84         order_keys[N_("signal")] = order_key_cnt++;
85         _active = true;
86         _silent = false;
87         _meter_point = MeterPostFader;
88         _initial_delay = 0;
89         _roll_delay = 0;
90         _own_latency = 0;
91         _have_internal_generator = false;
92         _declickable = false;
93         _pending_declick = true;
94         _remote_control_id = 0;
95         
96         _edit_group = 0;
97         _mix_group = 0;
98
99         _mute_affects_pre_fader = Config->get_mute_affects_pre_fader();
100         _mute_affects_post_fader = Config->get_mute_affects_post_fader();
101         _mute_affects_control_outs = Config->get_mute_affects_control_outs();
102         _mute_affects_main_outs = Config->get_mute_affects_main_outs();
103         
104         solo_gain = 1.0;
105         desired_solo_gain = 1.0;
106         mute_gain = 1.0;
107         desired_mute_gain = 1.0;
108
109         _control_outs = 0;
110
111         input_changed.connect (mem_fun (this, &Route::input_change_handler));
112         output_changed.connect (mem_fun (this, &Route::output_change_handler));
113 }
114
115 Route::~Route ()
116 {
117         clear_redirects (this);
118
119         if (_control_outs) {
120                 delete _control_outs;
121         }
122 }
123
124 void
125 Route::set_remote_control_id (uint32_t id)
126 {
127         if (id != _remote_control_id) {
128                 _remote_control_id = id;
129                 RemoteControlIDChanged ();
130         }
131 }
132
133 uint32_t
134 Route::remote_control_id() const
135 {
136         return _remote_control_id;
137 }
138
139 long
140 Route::order_key (string name) const
141 {
142         OrderKeys::const_iterator i;
143         
144         if ((i = order_keys.find (name)) == order_keys.end()) {
145                 return -1;
146         }
147
148         return (*i).second;
149 }
150
151 void
152 Route::set_order_key (string name, long n)
153 {
154         order_keys[name] = n;
155         _session.set_dirty ();
156 }
157
158 void
159 Route::inc_gain (gain_t fraction, void *src)
160 {
161         IO::inc_gain (fraction, src);
162 }
163
164 void
165 Route::set_gain (gain_t val, void *src)
166 {
167         if (src != 0 && _mix_group && src != _mix_group && _mix_group->is_active()) {
168                 
169                 if (_mix_group->is_relative()) {
170                         
171                         
172                         gain_t usable_gain  = gain();
173                         if (usable_gain < 0.000001f) {
174                                 usable_gain=0.000001f;
175                         }
176                                                 
177                         gain_t delta = val;
178                         if (delta < 0.000001f) {
179                                 delta=0.000001f;
180                         }
181
182                         delta -= usable_gain;
183
184                         if (delta == 0.0f) return;
185
186                         gain_t factor = delta / usable_gain;
187
188                         if (factor > 0.0f) {
189                                 factor = _mix_group->get_max_factor(factor);
190                                 if (factor == 0.0f) {
191                                         gain_changed (src);
192                                         return;
193                                 }
194                         } else {
195                                 factor = _mix_group->get_min_factor(factor);
196                                 if (factor == 0.0f) {
197                                         gain_changed (src);
198                                         return;
199                                 }
200                         }
201                                         
202                         _mix_group->apply (&Route::inc_gain, factor, _mix_group);
203
204                 } else {
205                         
206                         _mix_group->apply (&Route::set_gain, val, _mix_group);
207                 }
208
209                 return;
210         } 
211
212         if (val == gain()) {
213                 return;
214         }
215
216         IO::set_gain (val, src);
217 }
218
219 /** Process this route for one (sub) cycle (process thread)
220  *
221  * @param bufs Scratch buffers to use for the signal path
222  * @param start_frame Initial transport frame 
223  * @param end_frame Final transport frame
224  * @param nframes Number of frames to output (to ports)
225  * @param offset Output offset (of port buffers, for split cycles)
226  *
227  * Note that (end_frame - start_frame) may not be equal to nframes when the
228  * transport speed isn't 1.0 (eg varispeed).
229  */
230 void
231 Route::process_output_buffers (BufferSet& bufs,
232                 nframes_t start_frame, nframes_t end_frame, 
233         nframes_t nframes, nframes_t offset, bool with_redirects, int declick,
234                 bool meter)
235 {
236         // This is definitely very audio-only for now
237         assert(_default_type == DataType::AUDIO);
238         
239         RedirectList::iterator i;
240         bool post_fader_work = false;
241         bool mute_declick_applied = false;
242         gain_t dmg, dsg, dg;
243         IO *co;
244         bool mute_audible;
245         bool solo_audible;
246         bool no_monitor;
247         gain_t* gab = _session.gain_automation_buffer();
248
249         switch (Config->get_monitoring_model()) {
250         case HardwareMonitoring:
251         case ExternalMonitoring:
252                 no_monitor = true;
253                 break;
254         default:
255                 no_monitor = false;
256         }
257
258         declick = _pending_declick;
259
260         {
261                 Glib::Mutex::Lock cm (control_outs_lock, Glib::TRY_LOCK);
262                 
263                 if (cm.locked()) {
264                         co = _control_outs;
265                 } else {
266                         co = 0;
267                 }
268         }
269         
270         { 
271                 Glib::Mutex::Lock dm (declick_lock, Glib::TRY_LOCK);
272                 
273                 if (dm.locked()) {
274                         dmg = desired_mute_gain;
275                         dsg = desired_solo_gain;
276                         dg = _desired_gain;
277                 } else {
278                         dmg = mute_gain;
279                         dsg = solo_gain;
280                         dg = _gain;
281                 }
282         }
283
284         /* ----------------------------------------------------------------------------------------------------
285            GLOBAL DECLICK (for transport changes etc.)
286            -------------------------------------------------------------------------------------------------- */
287
288         if (declick > 0) {
289                 Amp::run (bufs, nframes, 0.0, 1.0, false);
290                 _pending_declick = 0;
291         } else if (declick < 0) {
292                 Amp::run (bufs, nframes, 1.0, 0.0, false);
293                 _pending_declick = 0;
294         } else {
295
296                 /* no global declick */
297
298                 if (solo_gain != dsg) {
299                         Amp::run (bufs, nframes, solo_gain, dsg, false);
300                         solo_gain = dsg;
301                 }
302         }
303
304
305         /* ----------------------------------------------------------------------------------------------------
306            INPUT METERING & MONITORING
307            -------------------------------------------------------------------------------------------------- */
308
309         if (meter && (_meter_point == MeterInput)) {
310                 _meter->run(bufs, nframes);
311         }
312
313         if (!_soloed && _mute_affects_pre_fader && (mute_gain != dmg)) {
314                 Amp::run (bufs, nframes, mute_gain, dmg, false);
315                 mute_gain = dmg;
316                 mute_declick_applied = true;
317         }
318
319         if ((_meter_point == MeterInput) && co) {
320                 
321                 solo_audible = dsg > 0;
322                 mute_audible = dmg > 0;// || !_mute_affects_pre_fader;
323                 
324                 if (    // muted by solo of another track
325                         
326                         !solo_audible || 
327                         
328                         // muted by mute of this track 
329                         
330                         !mute_audible ||
331                         
332                         // rec-enabled but not s/w monitoring 
333                         
334                         // TODO: this is probably wrong
335
336                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
337
338                         ) {
339                         
340                         co->silence (nframes, offset);
341                         
342                 } else {
343
344                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
345                         
346                 } 
347         } 
348
349         /* ---------------------------------------------------------------------------------------------------
350            PRE-FADER REDIRECTS
351            -------------------------------------------------------------------------------------------------- */
352
353         /* FIXME: Somewhere in these loops is where bufs.count() should go from n_inputs() to redirect_max_outs()
354          * (if they differ).  Something explicit needs to be done here to make sure the list of redirects will
355          * give us what we need (possibly by inserting transparent 'translators' into the list to make it work) */
356
357         if (with_redirects) {
358                 Glib::RWLock::ReaderLock rm (redirect_lock, Glib::TRY_LOCK);
359                 if (rm.locked()) {
360                         if (mute_gain > 0 || !_mute_affects_pre_fader) {
361                                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
362                                         switch ((*i)->placement()) {
363                                         case PreFader:
364                                                 (*i)->run (bufs, start_frame, end_frame, nframes, offset);
365                                                 break;
366                                         case PostFader:
367                                                 post_fader_work = true;
368                                                 break;
369                                         }
370                                 }
371                         } else {
372                                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
373                                         switch ((*i)->placement()) {
374                                         case PreFader:
375                                                 (*i)->silence (nframes, offset);
376                                                 break;
377                                         case PostFader:
378                                                 post_fader_work = true;
379                                                 break;
380                                         }
381                                 }
382                         }
383                 } 
384         }
385
386         // FIXME: for now, just hope the redirects list did what it was supposed to
387         bufs.set_count(n_process_buffers());
388
389         
390         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_post_fader) {
391                 Amp::run (bufs, nframes, mute_gain, dmg, false);
392                 mute_gain = dmg;
393                 mute_declick_applied = true;
394         }
395
396         /* ----------------------------------------------------------------------------------------------------
397            PRE-FADER METERING & MONITORING
398            -------------------------------------------------------------------------------------------------- */
399
400         if (meter && (_meter_point == MeterPreFader)) {
401                 _meter->run(bufs, nframes);
402         }
403
404         
405         if ((_meter_point == MeterPreFader) && co) {
406                 
407                 solo_audible = dsg > 0;
408                 mute_audible = dmg > 0 || !_mute_affects_pre_fader;
409                 
410                 if ( // muted by solo of another track
411                         
412                         !solo_audible || 
413                         
414                         // muted by mute of this track 
415                         
416                         !mute_audible ||
417                         
418                         // rec-enabled but not s/w monitoring 
419                         
420                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
421
422                         ) {
423                         
424                         co->silence (nframes, offset);
425                         
426                 } else {
427
428                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
429                         
430                 } 
431         } 
432         
433         /* ----------------------------------------------------------------------------------------------------
434            GAIN STAGE
435            -------------------------------------------------------------------------------------------------- */
436
437         /* if not recording or recording and requiring any monitor signal, then apply gain */
438
439         if ( // not recording 
440
441                 !(record_enabled() && _session.actively_recording()) || 
442                 
443             // OR recording 
444                 
445                 // h/w monitoring not in use 
446                 
447                 (!Config->get_monitoring_model() == HardwareMonitoring && 
448
449                  // AND software monitoring required
450
451                  Config->get_monitoring_model() == SoftwareMonitoring)) { 
452                 
453                 if (apply_gain_automation) {
454                         
455                         if (_phase_invert) {
456                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
457                                         Sample* const sp = i->data(nframes);
458                                         
459                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
460                                                 sp[nx] *= -gab[nx];
461                                         }
462                                 }
463                         } else {
464                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
465                                         Sample* const sp = i->data(nframes);
466                                         
467                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
468                                                 sp[nx] *= gab[nx];
469                                         }
470                                 }
471                         }
472                         
473                         if (apply_gain_automation && _session.transport_rolling() && nframes > 0) {
474                                 _effective_gain = gab[nframes-1];
475                         }
476                         
477                 } else {
478                         
479                         /* manual (scalar) gain */
480                         
481                         if (_gain != dg) {
482                                 
483                                 Amp::run (bufs, nframes, _gain, dg, _phase_invert);
484                                 _gain = dg;
485                                 
486                         } else if (_gain != 0 && (_phase_invert || _gain != 1.0)) {
487                                 
488                                 /* no need to interpolate current gain value,
489                                    but its non-unity, so apply it. if the gain
490                                    is zero, do nothing because we'll ship silence
491                                    below.
492                                 */
493
494                                 gain_t this_gain;
495                                 
496                                 if (_phase_invert) {
497                                         this_gain = -_gain;
498                                 } else {
499                                         this_gain = _gain;
500                                 }
501                                 
502                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
503                                         Sample* const sp = i->data(nframes);
504                                         Session::apply_gain_to_buffer(sp,nframes,this_gain);
505                                 }
506
507                         } else if (_gain == 0) {
508                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
509                                         i->clear();
510                                 }
511                         }
512                 }
513
514         } else {
515
516                 /* actively recording, no monitoring required; leave buffers as-is to save CPU cycles */
517
518         }
519
520         /* ----------------------------------------------------------------------------------------------------
521            POST-FADER REDIRECTS
522            -------------------------------------------------------------------------------------------------- */
523
524         /* note that post_fader_work cannot be true unless with_redirects was also true, so don't test both */
525
526         if (post_fader_work) {
527
528                 Glib::RWLock::ReaderLock rm (redirect_lock, Glib::TRY_LOCK);
529                 if (rm.locked()) {
530                         if (mute_gain > 0 || !_mute_affects_post_fader) {
531                                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
532                                         switch ((*i)->placement()) {
533                                         case PreFader:
534                                                 break;
535                                         case PostFader:
536                                                 (*i)->run (bufs, start_frame, end_frame, nframes, offset);
537                                                 break;
538                                         }
539                                 }
540                         } else {
541                                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
542                                         switch ((*i)->placement()) {
543                                         case PreFader:
544                                                 break;
545                                         case PostFader:
546                                                 (*i)->silence (nframes, offset);
547                                                 break;
548                                         }
549                                 }
550                         }
551                 } 
552         }
553
554         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_control_outs) {
555                 Amp::run (bufs, nframes, mute_gain, dmg, false);
556                 mute_gain = dmg;
557                 mute_declick_applied = true;
558         }
559
560         /* ----------------------------------------------------------------------------------------------------
561            CONTROL OUTPUT STAGE
562            -------------------------------------------------------------------------------------------------- */
563
564         if ((_meter_point == MeterPostFader) && co) {
565                 
566                 solo_audible = solo_gain > 0;
567                 mute_audible = dmg > 0 || !_mute_affects_control_outs;
568
569                 if ( // silent anyway
570
571                         (_gain == 0 && !apply_gain_automation) || 
572                     
573                      // muted by solo of another track
574
575                         !solo_audible || 
576                     
577                      // muted by mute of this track 
578
579                         !mute_audible ||
580
581                     // recording but not s/w monitoring 
582                         
583                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
584
585                         ) {
586
587                         co->silence (nframes, offset);
588                         
589                 } else {
590
591                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
592                 } 
593         } 
594
595         /* ----------------------------------------------------------------------
596            GLOBAL MUTE 
597            ----------------------------------------------------------------------*/
598
599         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_main_outs) {
600                 Amp::run (bufs, nframes, mute_gain, dmg, false);
601                 mute_gain = dmg;
602                 mute_declick_applied = true;
603         }
604         
605         /* ----------------------------------------------------------------------------------------------------
606            MAIN OUTPUT STAGE
607            -------------------------------------------------------------------------------------------------- */
608
609         solo_audible = dsg > 0;
610         mute_audible = dmg > 0 || !_mute_affects_main_outs;
611         
612         if (n_outputs().get(_default_type) == 0) {
613             
614             /* relax */
615
616         } else if (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording())) {
617                 
618                 IO::silence (nframes, offset);
619                 
620         } else {
621
622                 if ( // silent anyway
623
624                     (_gain == 0 && !apply_gain_automation) ||
625                     
626                     // muted by solo of another track, but not using control outs for solo
627
628                     (!solo_audible && (Config->get_solo_model() != SoloBus)) ||
629                     
630                     // muted by mute of this track
631
632                     !mute_audible
633
634                         ) {
635
636                         /* don't use Route::silence() here, because that causes
637                            all outputs (sends, port inserts, etc. to be silent).
638                         */
639                         
640                         if (_meter_point == MeterPostFader) {
641                                 peak_meter().reset();
642                         }
643                         
644                         IO::silence (nframes, offset);
645                         
646                 } else {
647                         
648                         deliver_output(bufs, start_frame, end_frame, nframes, offset);
649
650                 }
651
652         }
653
654         /* ----------------------------------------------------------------------------------------------------
655            POST-FADER METERING
656            -------------------------------------------------------------------------------------------------- */
657
658         if (meter && (_meter_point == MeterPostFader)) {
659                 if ((_gain == 0 && !apply_gain_automation) || dmg == 0) {
660                         _meter->reset();
661                 } else {
662                         _meter->run(output_buffers(), nframes, offset);
663                 }
664         }
665 }
666
667 ChanCount
668 Route::n_process_buffers ()
669 {
670         return max (n_inputs(), redirect_max_outs);
671 }
672
673 void
674 Route::passthru (nframes_t start_frame, nframes_t end_frame, nframes_t nframes, nframes_t offset, int declick, bool meter_first)
675 {
676         BufferSet& bufs = _session.get_scratch_buffers(n_process_buffers());
677
678         _silent = false;
679
680         collect_input (bufs, nframes, offset);
681
682 #define meter_stream meter_first
683
684         if (meter_first) {
685                 _meter->run(bufs, nframes);
686                 meter_stream = false;
687         } else {
688                 meter_stream = true;
689         }
690                 
691         process_output_buffers (bufs, start_frame, end_frame, nframes, offset, true, declick, meter_stream);
692
693 #undef meter_stream
694 }
695
696 void
697 Route::passthru_silence (jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t nframes, jack_nframes_t offset, int declick, bool meter)
698 {
699         process_output_buffers (_session.get_silent_buffers (n_process_buffers()), start_frame, end_frame, nframes, offset, true, declick, meter);
700 }
701
702 void
703 Route::set_solo (bool yn, void *src)
704 {
705         if (_solo_safe) {
706                 return;
707         }
708
709         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
710                 _mix_group->apply (&Route::set_solo, yn, _mix_group);
711                 return;
712         }
713
714         if (_soloed != yn) {
715                 _soloed = yn;
716                 solo_changed (src); /* EMIT SIGNAL */
717                 _solo_control.Changed (); /* EMIT SIGNAL */
718         }
719 }
720
721 void
722 Route::set_solo_mute (bool yn)
723 {
724         Glib::Mutex::Lock lm (declick_lock);
725
726         /* Called by Session in response to another Route being soloed.
727          */
728            
729         desired_solo_gain = (yn?0.0:1.0);
730 }
731
732 void
733 Route::set_solo_safe (bool yn, void *src)
734 {
735         if (_solo_safe != yn) {
736                 _solo_safe = yn;
737                  solo_safe_changed (src); /* EMIT SIGNAL */
738         }
739 }
740
741 void
742 Route::set_mute (bool yn, void *src)
743
744 {
745         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
746                 _mix_group->apply (&Route::set_mute, yn, _mix_group);
747                 return;
748         }
749
750         if (_muted != yn) {
751                 _muted = yn;
752                 mute_changed (src); /* EMIT SIGNAL */
753                 
754                 _mute_control.Changed (); /* EMIT SIGNAL */
755                 
756                 Glib::Mutex::Lock lm (declick_lock);
757                 desired_mute_gain = (yn?0.0f:1.0f);
758         }
759 }
760
761 int
762 Route::add_redirect (boost::shared_ptr<Redirect> redirect, void *src, uint32_t* err_streams)
763 {
764         ChanCount old_rmo = redirect_max_outs;
765
766         if (!_session.engine().connected()) {
767                 return 1;
768         }
769
770         {
771                 Glib::RWLock::WriterLock lm (redirect_lock);
772
773                 boost::shared_ptr<PluginInsert> pi;
774                 boost::shared_ptr<PortInsert> porti;
775
776                 redirect->set_default_type(_default_type);
777
778                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(redirect)) != 0) {
779                         pi->set_count (1);
780
781                         if (pi->input_streams() == ChanCount::ZERO) {
782                                 /* generator plugin */
783                                 _have_internal_generator = true;
784                         }
785                         
786                 } else if ((porti = boost::dynamic_pointer_cast<PortInsert>(redirect)) != 0) {
787
788                         /* force new port inserts to start out with an i/o configuration
789                            that matches this route's i/o configuration.
790
791                            the "inputs" for the port are supposed to match the output
792                            of this route.
793
794                            the "outputs" of the route should match the inputs of this
795                            route. XXX shouldn't they match the number of active signal
796                            streams at the point of insertion?
797                         */
798                         // FIXME: (yes, they should)
799
800                         porti->ensure_io (n_outputs (), n_inputs(), false, this);
801                 }
802                 
803                 // Ensure peak vector sizes before the plugin is activated
804                 ChanCount potential_max_streams = max(redirect->input_streams(), redirect->output_streams());
805                 _meter->setup(potential_max_streams);
806
807                 _redirects.push_back (redirect);
808
809                 if (_reset_plugin_counts (err_streams)) {
810                         _redirects.pop_back ();
811                         _reset_plugin_counts (0); // it worked before we tried to add it ...
812                         return -1;
813                 }
814
815                 redirect->activate ();
816                 redirect->active_changed.connect (mem_fun (*this, &Route::redirect_active_proxy));
817         }
818         
819         if (redirect_max_outs != old_rmo || old_rmo == ChanCount::ZERO) {
820                 reset_panner ();
821         }
822
823
824         redirects_changed (src); /* EMIT SIGNAL */
825         return 0;
826 }
827
828 int
829 Route::add_redirects (const RedirectList& others, void *src, uint32_t* err_streams)
830 {
831         ChanCount old_rmo = redirect_max_outs;
832
833         if (!_session.engine().connected()) {
834                 return 1;
835         }
836
837         {
838                 Glib::RWLock::WriterLock lm (redirect_lock);
839
840                 RedirectList::iterator existing_end = _redirects.end();
841                 --existing_end;
842
843                 ChanCount potential_max_streams;
844
845                 for (RedirectList::const_iterator i = others.begin(); i != others.end(); ++i) {
846                         
847                         boost::shared_ptr<PluginInsert> pi;
848                         
849                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
850                                 pi->set_count (1);
851                                 
852                                 ChanCount m = max(pi->input_streams(), pi->output_streams());
853                                 if (m > potential_max_streams)
854                                         potential_max_streams = m;
855                         }
856
857                         // Ensure peak vector sizes before the plugin is activated
858                         _meter->setup(potential_max_streams);
859
860                         _redirects.push_back (*i);
861                         
862                         if (_reset_plugin_counts (err_streams)) {
863                                 ++existing_end;
864                                 _redirects.erase (existing_end, _redirects.end());
865                                 _reset_plugin_counts (0); // it worked before we tried to add it ...
866                                 return -1;
867                         }
868                         
869                         (*i)->activate ();
870                         (*i)->active_changed.connect (mem_fun (*this, &Route::redirect_active_proxy));
871                 }
872         }
873         
874         if (redirect_max_outs != old_rmo || old_rmo == ChanCount::ZERO) {
875                 reset_panner ();
876         }
877
878         redirects_changed (src); /* EMIT SIGNAL */
879         return 0;
880 }
881
882 void
883 Route::clear_redirects (void *src)
884 {
885         ChanCount old_rmo = redirect_max_outs;
886
887         if (!_session.engine().connected()) {
888                 return;
889         }
890
891         {
892                 Glib::RWLock::WriterLock lm (redirect_lock);
893                 RedirectList::iterator i;
894                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
895                         (*i)->drop_references ();
896                 }
897                 _redirects.clear ();
898         }
899
900         if (redirect_max_outs != old_rmo) {
901                 reset_panner ();
902         }
903         
904         redirect_max_outs.reset();
905         _have_internal_generator = false;
906         redirects_changed (src); /* EMIT SIGNAL */
907 }
908
909 int
910 Route::remove_redirect (boost::shared_ptr<Redirect> redirect, void *src, uint32_t* err_streams)
911 {
912         ChanCount old_rmo = redirect_max_outs;
913
914         if (!_session.engine().connected()) {
915                 return 1;
916         }
917
918         redirect_max_outs.reset();
919
920         {
921                 Glib::RWLock::WriterLock lm (redirect_lock);
922                 RedirectList::iterator i;
923                 bool removed = false;
924
925                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
926                         if (*i == redirect) {
927
928                                 RedirectList::iterator tmp;
929
930                                 /* move along, see failure case for reset_plugin_counts()
931                                    where we may need to reinsert the redirect.
932                                 */
933
934                                 tmp = i;
935                                 ++tmp;
936
937                                 /* stop redirects that send signals to JACK ports
938                                    from causing noise as a result of no longer being
939                                    run.
940                                 */
941
942                                 boost::shared_ptr<Send> send;
943                                 boost::shared_ptr<PortInsert> port_insert;
944                                 
945                                 if ((send = boost::dynamic_pointer_cast<Send> (*i)) != 0) {
946                                         send->disconnect_inputs (this);
947                                         send->disconnect_outputs (this);
948                                 } else if ((port_insert = boost::dynamic_pointer_cast<PortInsert> (*i)) != 0) {
949                                         port_insert->disconnect_inputs (this);
950                                         port_insert->disconnect_outputs (this);
951                                 }
952
953                                 _redirects.erase (i);
954
955                                 i = tmp;
956                                 removed = true;
957                                 break;
958                         }
959                 }
960
961                 if (!removed) {
962                         /* what? */
963                         return 1;
964                 }
965
966                 if (_reset_plugin_counts (err_streams)) {
967                         /* get back to where we where */
968                         _redirects.insert (i, redirect);
969                         /* we know this will work, because it worked before :) */
970                         _reset_plugin_counts (0);
971                         return -1;
972                 }
973
974                 bool foo = false;
975
976                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
977                         boost::shared_ptr<PluginInsert> pi;
978                         
979                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
980                                 if (pi->is_generator()) {
981                                         foo = true;
982                                 }
983                         }
984                 }
985
986                 _have_internal_generator = foo;
987         }
988
989         if (old_rmo != redirect_max_outs) {
990                 reset_panner ();
991         }
992
993         redirect->drop_references ();
994
995         redirects_changed (src); /* EMIT SIGNAL */
996         return 0;
997 }
998
999 int
1000 Route::reset_plugin_counts (uint32_t* lpc)
1001 {
1002         Glib::RWLock::WriterLock lm (redirect_lock);
1003         return _reset_plugin_counts (lpc);
1004 }
1005
1006
1007 int
1008 Route::_reset_plugin_counts (uint32_t* err_streams)
1009 {
1010         RedirectList::iterator r;
1011         uint32_t i_cnt;
1012         uint32_t s_cnt;
1013         map<Placement,list<InsertCount> > insert_map;
1014         nframes_t initial_streams;
1015
1016         redirect_max_outs.reset();
1017         i_cnt = 0;
1018         s_cnt = 0;
1019
1020         /* divide inserts up by placement so we get the signal flow
1021            properly modelled. we need to do this because the _redirects
1022            list is not sorted by placement, and because other reasons may 
1023            exist now or in the future for this separate treatment.
1024         */
1025         
1026         for (r = _redirects.begin(); r != _redirects.end(); ++r) {
1027
1028                 boost::shared_ptr<Insert> insert;
1029
1030                 /* do this here in case we bomb out before we get to the end of
1031                    this function.
1032                 */
1033
1034                 redirect_max_outs = max ((*r)->output_streams (), redirect_max_outs);
1035
1036                 if ((insert = boost::dynamic_pointer_cast<Insert>(*r)) != 0) {
1037                         ++i_cnt;
1038                         insert_map[insert->placement()].push_back (InsertCount (insert));
1039
1040                         /* reset plugin counts back to one for now so
1041                            that we have a predictable, controlled
1042                            state to try to configure.
1043                         */
1044
1045                         boost::shared_ptr<PluginInsert> pi;
1046                 
1047                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(insert)) != 0) {
1048                                 pi->set_count (1);
1049                         }
1050
1051                 } else if (boost::dynamic_pointer_cast<Send> (*r) != 0) {
1052                         ++s_cnt;
1053                 }
1054         }
1055         
1056         if (i_cnt == 0) {
1057                 if (s_cnt) {
1058                         goto recompute;
1059                 } else {
1060                         return 0;
1061                 }
1062         }
1063
1064         /* Now process each placement in order, checking to see if we 
1065            can really do what has been requested.
1066         */
1067
1068         /* A: PreFader */
1069         
1070         if (check_some_plugin_counts (insert_map[PreFader], n_inputs ().get(_default_type), err_streams)) {
1071                 return -1;
1072         }
1073
1074         /* figure out the streams that will feed into PreFader */
1075
1076         if (!insert_map[PreFader].empty()) {
1077                 InsertCount& ic (insert_map[PreFader].back());
1078                 initial_streams = ic.insert->compute_output_streams (ic.cnt);
1079         } else {
1080                 initial_streams = n_inputs ().get(_default_type);
1081         }
1082
1083         /* B: PostFader */
1084
1085         if (check_some_plugin_counts (insert_map[PostFader], initial_streams, err_streams)) {
1086                 return -1;
1087         }
1088
1089         /* OK, everything can be set up correctly, so lets do it */
1090
1091         apply_some_plugin_counts (insert_map[PreFader]);
1092         apply_some_plugin_counts (insert_map[PostFader]);
1093
1094         /* recompute max outs of any redirect */
1095
1096   recompute:
1097
1098         redirect_max_outs.reset();
1099         RedirectList::iterator prev = _redirects.end();
1100
1101         for (r = _redirects.begin(); r != _redirects.end(); prev = r, ++r) {
1102                 boost::shared_ptr<Send> s;
1103
1104                 if ((s = boost::dynamic_pointer_cast<Send> (*r)) != 0) {
1105                         if (r == _redirects.begin()) {
1106                                 s->expect_inputs (n_inputs());
1107                         } else {
1108                                 s->expect_inputs ((*prev)->output_streams());
1109                         }
1110                 }
1111
1112                 redirect_max_outs = max ((*r)->output_streams(), redirect_max_outs);
1113         }
1114
1115         /* we're done */
1116
1117         return 0;
1118 }                                  
1119
1120 int32_t
1121 Route::apply_some_plugin_counts (list<InsertCount>& iclist)
1122 {
1123         list<InsertCount>::iterator i;
1124
1125         for (i = iclist.begin(); i != iclist.end(); ++i) {
1126                 
1127                 if ((*i).insert->configure_io ((*i).cnt, (*i).in, (*i).out)) {
1128                         return -1;
1129                 }
1130                 /* make sure that however many we have, they are all active */
1131                 (*i).insert->activate ();
1132         }
1133
1134         return 0;
1135 }
1136
1137 int32_t
1138 Route::check_some_plugin_counts (list<InsertCount>& iclist, int32_t required_inputs, uint32_t* err_streams)
1139 {
1140         list<InsertCount>::iterator i;
1141         
1142         for (i = iclist.begin(); i != iclist.end(); ++i) {
1143
1144                 if (((*i).cnt = (*i).insert->can_support_input_configuration (required_inputs)) < 0) {
1145                         if (err_streams) {
1146                                 *err_streams = required_inputs;
1147                         }
1148                         return -1;
1149                 }
1150                 
1151                 (*i).in = required_inputs;
1152                 (*i).out = (*i).insert->compute_output_streams ((*i).cnt);
1153
1154                 required_inputs = (*i).out;
1155         }
1156
1157         return 0;
1158 }
1159
1160 int
1161 Route::copy_redirects (const Route& other, Placement placement, uint32_t* err_streams)
1162 {
1163         ChanCount old_rmo = redirect_max_outs;
1164
1165         if (err_streams) {
1166                 *err_streams = 0;
1167         }
1168
1169         RedirectList to_be_deleted;
1170
1171         {
1172                 Glib::RWLock::WriterLock lm (redirect_lock);
1173                 RedirectList::iterator tmp;
1174                 RedirectList the_copy;
1175
1176                 the_copy = _redirects;
1177                 
1178                 /* remove all relevant redirects */
1179
1180                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1181                         tmp = i;
1182                         ++tmp;
1183
1184                         if ((*i)->placement() == placement) {
1185                                 to_be_deleted.push_back (*i);
1186                                 _redirects.erase (i);
1187                         }
1188
1189                         i = tmp;
1190                 }
1191
1192                 /* now copy the relevant ones from "other" */
1193                 
1194                 for (RedirectList::const_iterator i = other._redirects.begin(); i != other._redirects.end(); ++i) {
1195                         if ((*i)->placement() == placement) {
1196                                 _redirects.push_back (Redirect::clone (*i));
1197                         }
1198                 }
1199
1200                 /* reset plugin stream handling */
1201
1202                 if (_reset_plugin_counts (err_streams)) {
1203
1204                         /* FAILED COPY ATTEMPT: we have to restore order */
1205
1206                         /* delete all cloned redirects */
1207
1208                         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1209
1210                                 tmp = i;
1211                                 ++tmp;
1212
1213                                 if ((*i)->placement() == placement) {
1214                                         _redirects.erase (i);
1215                                 }
1216                                 
1217                                 i = tmp;
1218                         }
1219
1220                         /* restore the natural order */
1221
1222                         _redirects = the_copy;
1223                         redirect_max_outs = old_rmo;
1224
1225                         /* we failed, even though things are OK again */
1226
1227                         return -1;
1228
1229                 } else {
1230                         
1231                         /* SUCCESSFUL COPY ATTEMPT: delete the redirects we removed pre-copy */
1232                         to_be_deleted.clear ();
1233                 }
1234         }
1235
1236         if (redirect_max_outs != old_rmo || old_rmo == ChanCount::ZERO) {
1237                 reset_panner ();
1238         }
1239
1240         redirects_changed (this); /* EMIT SIGNAL */
1241         return 0;
1242 }
1243
1244 void
1245 Route::all_redirects_flip ()
1246 {
1247         Glib::RWLock::ReaderLock lm (redirect_lock);
1248
1249         if (_redirects.empty()) {
1250                 return;
1251         }
1252
1253         bool first_is_on = _redirects.front()->active();
1254         
1255         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1256                 (*i)->set_active (!first_is_on, this);
1257         }
1258 }
1259
1260 void
1261 Route::all_redirects_active (bool state)
1262 {
1263         Glib::RWLock::ReaderLock lm (redirect_lock);
1264
1265         if (_redirects.empty()) {
1266                 return;
1267         }
1268
1269         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1270                 (*i)->set_active (state, this);
1271         }
1272 }
1273
1274 struct RedirectSorter {
1275     bool operator() (boost::shared_ptr<const Redirect> a, boost::shared_ptr<const Redirect> b) {
1276             return a->sort_key() < b->sort_key();
1277     }
1278 };
1279
1280 int
1281 Route::sort_redirects (uint32_t* err_streams)
1282 {
1283         {
1284                 RedirectSorter comparator;
1285                 Glib::RWLock::WriterLock lm (redirect_lock);
1286                 ChanCount old_rmo = redirect_max_outs;
1287
1288                 /* the sweet power of C++ ... */
1289
1290                 RedirectList as_it_was_before = _redirects;
1291
1292                 _redirects.sort (comparator);
1293         
1294                 if (_reset_plugin_counts (err_streams)) {
1295                         _redirects = as_it_was_before;
1296                         redirect_max_outs = old_rmo;
1297                         return -1;
1298                 } 
1299         } 
1300
1301         reset_panner ();
1302         redirects_changed (this); /* EMIT SIGNAL */
1303
1304         return 0;
1305 }
1306
1307 XMLNode&
1308 Route::get_state()
1309 {
1310         return state(true);
1311 }
1312
1313 XMLNode&
1314 Route::get_template()
1315 {
1316         return state(false);
1317 }
1318
1319 XMLNode&
1320 Route::state(bool full_state)
1321 {
1322         XMLNode *node = new XMLNode("Route");
1323         RedirectList:: iterator i;
1324         char buf[32];
1325
1326         if (_flags) {
1327                 node->add_property("flags", enum_2_string (_flags));
1328         }
1329         
1330         node->add_property("default-type", _default_type.to_string());
1331
1332         node->add_property("active", _active?"yes":"no");
1333         node->add_property("muted", _muted?"yes":"no");
1334         node->add_property("soloed", _soloed?"yes":"no");
1335         node->add_property("phase-invert", _phase_invert?"yes":"no");
1336         node->add_property("mute-affects-pre-fader", _mute_affects_pre_fader?"yes":"no"); 
1337         node->add_property("mute-affects-post-fader", _mute_affects_post_fader?"yes":"no"); 
1338         node->add_property("mute-affects-control-outs", _mute_affects_control_outs?"yes":"no"); 
1339         node->add_property("mute-affects-main-outs", _mute_affects_main_outs?"yes":"no"); 
1340
1341         if (_edit_group) {
1342                 node->add_property("edit-group", _edit_group->name());
1343         }
1344         if (_mix_group) {
1345                 node->add_property("mix-group", _mix_group->name());
1346         }
1347
1348         string order_string;
1349         OrderKeys::iterator x = order_keys.begin(); 
1350
1351         while (x != order_keys.end()) {
1352                 order_string += (*x).first;
1353                 order_string += '=';
1354                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1355                 order_string += buf;
1356                 
1357                 ++x;
1358
1359                 if (x == order_keys.end()) {
1360                         break;
1361                 }
1362
1363                 order_string += ':';
1364         }
1365         node->add_property ("order-keys", order_string);
1366
1367         node->add_child_nocopy (IO::state (full_state));
1368         node->add_child_nocopy (_solo_control.get_state ());
1369         node->add_child_nocopy (_mute_control.get_state ());
1370
1371         if (_control_outs) {
1372                 XMLNode* cnode = new XMLNode (X_("ControlOuts"));
1373                 cnode->add_child_nocopy (_control_outs->state (full_state));
1374                 node->add_child_nocopy (*cnode);
1375         }
1376
1377         if (_comment.length()) {
1378                 XMLNode *cmt = node->add_child ("Comment");
1379                 cmt->add_content (_comment);
1380         }
1381
1382         for (i = _redirects.begin(); i != _redirects.end(); ++i) {
1383                 node->add_child_nocopy((*i)->state (full_state));
1384         }
1385
1386         if (_extra_xml){
1387                 node->add_child_copy (*_extra_xml);
1388         }
1389         
1390         return *node;
1391 }
1392
1393 void
1394 Route::set_deferred_state ()
1395 {
1396         XMLNodeList nlist;
1397         XMLNodeConstIterator niter;
1398
1399         if (!deferred_state) {
1400                 return;
1401         }
1402
1403         nlist = deferred_state->children();
1404
1405         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1406                 add_redirect_from_xml (**niter);
1407         }
1408
1409         delete deferred_state;
1410         deferred_state = 0;
1411 }
1412
1413 void
1414 Route::add_redirect_from_xml (const XMLNode& node)
1415 {
1416         const XMLProperty *prop;
1417
1418         if (node.name() == "Send") {
1419                 
1420
1421                 try {
1422                         boost::shared_ptr<Send> send (new Send (_session, node));
1423                         add_redirect (send, this);
1424                 } 
1425                 
1426                 catch (failed_constructor &err) {
1427                         error << _("Send construction failed") << endmsg;
1428                         return;
1429                 }
1430                 
1431         } else if (node.name() == "Insert") {
1432                 
1433                 try {
1434                         if ((prop = node.property ("type")) != 0) {
1435
1436                                 boost::shared_ptr<Insert> insert;
1437
1438                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || prop->value() == "vst") {
1439
1440                                         insert.reset (new PluginInsert(_session, node));
1441                                         
1442                                 } else if (prop->value() == "port") {
1443
1444
1445                                         insert.reset (new PortInsert (_session, node));
1446
1447                                 } else {
1448
1449                                         error << string_compose(_("unknown Insert type \"%1\"; ignored"), prop->value()) << endmsg;
1450                                 }
1451
1452                                 add_redirect (insert, this);
1453                                 
1454                         } else {
1455                                 error << _("Insert XML node has no type property") << endmsg;
1456                         }
1457                 }
1458                 
1459                 catch (failed_constructor &err) {
1460                         warning << _("insert could not be created. Ignored.") << endmsg;
1461                         return;
1462                 }
1463         }
1464 }
1465
1466 int
1467 Route::set_state (const XMLNode& node)
1468 {
1469         return _set_state (node, true);
1470 }
1471
1472 int
1473 Route::_set_state (const XMLNode& node, bool call_base)
1474 {
1475         XMLNodeList nlist;
1476         XMLNodeConstIterator niter;
1477         XMLNode *child;
1478         XMLPropertyList plist;
1479         const XMLProperty *prop;
1480
1481         if (node.name() != "Route"){
1482                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1483                 return -1;
1484         }
1485
1486         if ((prop = node.property (X_("flags"))) != 0) {
1487                 _flags = Flag (string_2_enum (prop->value(), _flags));
1488         } else {
1489                 _flags = Flag (0);
1490         }
1491         
1492         if ((prop = node.property (X_("default-type"))) != 0) {
1493                 _default_type = DataType(prop->value());
1494                 assert(_default_type != DataType::NIL);
1495         }
1496
1497         if ((prop = node.property (X_("phase-invert"))) != 0) {
1498                 set_phase_invert(prop->value()=="yes"?true:false, this);
1499         }
1500
1501         if ((prop = node.property (X_("active"))) != 0) {
1502                 set_active (prop->value() == "yes");
1503         }
1504
1505         if ((prop = node.property (X_("muted"))) != 0) {
1506                 bool yn = prop->value()=="yes"?true:false; 
1507
1508                 /* force reset of mute status */
1509
1510                 _muted = !yn;
1511                 set_mute(yn, this);
1512                 mute_gain = desired_mute_gain;
1513         }
1514
1515         if ((prop = node.property (X_("soloed"))) != 0) {
1516                 bool yn = prop->value()=="yes"?true:false; 
1517
1518                 /* force reset of solo status */
1519
1520                 _soloed = !yn;
1521                 set_solo (yn, this);
1522                 solo_gain = desired_solo_gain;
1523         }
1524
1525         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
1526                 _mute_affects_pre_fader = (prop->value()=="yes")?true:false;
1527         }
1528
1529         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
1530                 _mute_affects_post_fader = (prop->value()=="yes")?true:false;
1531         }
1532
1533         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
1534                 _mute_affects_control_outs = (prop->value()=="yes")?true:false;
1535         }
1536
1537         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
1538                 _mute_affects_main_outs = (prop->value()=="yes")?true:false;
1539         }
1540
1541         if ((prop = node.property (X_("edit-group"))) != 0) {
1542                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
1543                 if(edit_group == 0) {
1544                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1545                 } else {
1546                         set_edit_group(edit_group, this);
1547                 }
1548         }
1549
1550         if ((prop = node.property (X_("order-keys"))) != 0) {
1551
1552                 long n;
1553
1554                 string::size_type colon, equal;
1555                 string remaining = prop->value();
1556
1557                 while (remaining.length()) {
1558
1559                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1560                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1561                                       << endmsg;
1562                         } else {
1563                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1564                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1565                                               << endmsg;
1566                                 } else {
1567                                         set_order_key (remaining.substr (0, equal), n);
1568                                 }
1569                         }
1570
1571                         colon = remaining.find_first_of (':');
1572
1573                         if (colon != string::npos) {
1574                                 remaining = remaining.substr (colon+1);
1575                         } else {
1576                                 break;
1577                         }
1578                 }
1579         }
1580
1581         nlist = node.children();
1582
1583         if (deferred_state) {
1584                 delete deferred_state;
1585         }
1586
1587         deferred_state = new XMLNode(X_("deferred state"));
1588
1589         /* set parent class properties before anything else */
1590
1591         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1592
1593                 child = *niter;
1594
1595                 if (child->name() == IO::state_node_name && call_base) {
1596
1597                         IO::set_state (*child);
1598                         break;
1599                 }
1600         }
1601                         
1602         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1603
1604                 child = *niter;
1605                         
1606                 if (child->name() == X_("Send")) {
1607
1608
1609                         if (!IO::ports_legal) {
1610
1611                                 deferred_state->add_child_copy (*child);
1612
1613                         } else {
1614                                 add_redirect_from_xml (*child);
1615                         }
1616
1617                 } else if (child->name() == X_("Insert")) {
1618                         
1619                         if (!IO::ports_legal) {
1620                                 
1621                                 deferred_state->add_child_copy (*child);
1622
1623                         } else {
1624                                 
1625                                 add_redirect_from_xml (*child);
1626                         }
1627
1628                 } else if (child->name() == X_("Automation")) {
1629                         
1630                         if ((prop = child->property (X_("path"))) != 0)  {
1631                                 load_automation (prop->value());
1632                         }
1633
1634                 } else if (child->name() == X_("ControlOuts")) {
1635                         
1636                         string coutname = _name;
1637                         coutname += _("[control]");
1638
1639                         _control_outs = new IO (_session, coutname);
1640                         _control_outs->set_state (**(child->children().begin()));
1641
1642                 } else if (child->name() == X_("Comment")) {
1643
1644                         /* XXX this is a terrible API design in libxml++ */
1645
1646                         XMLNode *cmt = *(child->children().begin());
1647                         _comment = cmt->content();
1648
1649                 } else if (child->name() == X_("extra")) {
1650
1651                         _extra_xml = new XMLNode (*child);
1652
1653                 } else if (child->name() == X_("controllable") && (prop = child->property("name")) != 0) {
1654                         
1655                         if (prop->value() == "solo") {
1656                                 _solo_control.set_state (*child);
1657                                 _session.add_controllable (&_solo_control);
1658                         }
1659                         else if (prop->value() == "mute") {
1660                                 _mute_control.set_state (*child);
1661                                 _session.add_controllable (&_mute_control);
1662                         }
1663                 }
1664         }
1665
1666         if ((prop = node.property (X_("mix-group"))) != 0) {
1667                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
1668                 if (mix_group == 0) {
1669                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1670                 }  else {
1671                         set_mix_group(mix_group, this);
1672                 }
1673         }
1674
1675         return 0;
1676 }
1677
1678 void
1679 Route::curve_reallocate ()
1680 {
1681 //      _gain_automation_curve.finish_resize ();
1682 //      _pan_automation_curve.finish_resize ();
1683 }
1684
1685 void
1686 Route::silence (nframes_t nframes, nframes_t offset)
1687 {
1688         if (!_silent) {
1689
1690                 IO::silence (nframes, offset);
1691
1692                 if (_control_outs) {
1693                         _control_outs->silence (nframes, offset);
1694                 }
1695
1696                 { 
1697                         Glib::RWLock::ReaderLock lm (redirect_lock, Glib::TRY_LOCK);
1698                         
1699                         if (lm.locked()) {
1700                                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1701                                         boost::shared_ptr<PluginInsert> pi;
1702                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
1703                                                 // skip plugins, they don't need anything when we're not active
1704                                                 continue;
1705                                         }
1706
1707                                         (*i)->silence (nframes, offset);
1708                                 }
1709
1710                                 if (nframes == _session.get_block_size() && offset == 0) {
1711                                         // _silent = true;
1712                                 }
1713                         }
1714                 }
1715                 
1716         }
1717 }       
1718
1719 int
1720 Route::set_control_outs (const vector<string>& ports)
1721 {
1722         Glib::Mutex::Lock lm (control_outs_lock);
1723         vector<string>::const_iterator i;
1724
1725         if (_control_outs) {
1726                 delete _control_outs;
1727                 _control_outs = 0;
1728         }
1729         
1730         if (ports.empty()) {
1731                 return 0;
1732         }
1733  
1734         string coutname = _name;
1735         coutname += _("[control]");
1736         
1737         _control_outs = new IO (_session, coutname);
1738
1739         /* our control outs need as many outputs as we
1740            have audio outputs. we track the changes in ::output_change_handler().
1741         */
1742
1743         _control_outs->ensure_io (ChanCount::ZERO, ChanCount(DataType::AUDIO, n_outputs().get(DataType::AUDIO)), true, this);
1744  
1745         return 0;
1746 }       
1747
1748 void
1749 Route::set_edit_group (RouteGroup *eg, void *src)
1750
1751 {
1752         if (eg == _edit_group) {
1753                 return;
1754         }
1755
1756         if (_edit_group) {
1757                 _edit_group->remove (this);
1758         }
1759
1760         if ((_edit_group = eg) != 0) {
1761                 _edit_group->add (this);
1762         }
1763
1764         _session.set_dirty ();
1765         edit_group_changed (src); /* EMIT SIGNAL */
1766 }
1767
1768 void
1769 Route::drop_edit_group (void *src)
1770 {
1771         _edit_group = 0;
1772         _session.set_dirty ();
1773         edit_group_changed (src); /* EMIT SIGNAL */
1774 }
1775
1776 void
1777 Route::set_mix_group (RouteGroup *mg, void *src)
1778
1779 {
1780         if (mg == _mix_group) {
1781                 return;
1782         }
1783
1784         if (_mix_group) {
1785                 _mix_group->remove (this);
1786         }
1787
1788         if ((_mix_group = mg) != 0) {
1789                 _mix_group->add (this);
1790         }
1791
1792         _session.set_dirty ();
1793         mix_group_changed (src); /* EMIT SIGNAL */
1794 }
1795
1796 void
1797 Route::drop_mix_group (void *src)
1798 {
1799         _mix_group = 0;
1800         _session.set_dirty ();
1801         mix_group_changed (src); /* EMIT SIGNAL */
1802 }
1803
1804 void
1805 Route::set_comment (string cmt, void *src)
1806 {
1807         _comment = cmt;
1808         comment_changed (src);
1809         _session.set_dirty ();
1810 }
1811
1812 bool
1813 Route::feeds (boost::shared_ptr<Route> other)
1814 {
1815         uint32_t i, j;
1816
1817         IO& self = *this;
1818         uint32_t no = self.n_outputs().get_total();
1819         uint32_t ni = other->n_inputs ().get_total();
1820
1821         for (i = 0; i < no; ++i) {
1822                 for (j = 0; j < ni; ++j) {
1823                         if (self.output(i)->connected_to (other->input(j)->name())) {
1824                                 return true;
1825                         }
1826                 }
1827         }
1828
1829         /* check Redirects which may also interconnect Routes */
1830
1831         for (RedirectList::iterator r = _redirects.begin(); r != _redirects.end(); r++) {
1832
1833                 no = (*r)->n_outputs().get_total();
1834
1835                 for (i = 0; i < no; ++i) {
1836                         for (j = 0; j < ni; ++j) {
1837                                 if ((*r)->output(i)->connected_to (other->input (j)->name())) {
1838                                         return true;
1839                                 }
1840                         }
1841                 }
1842         }
1843
1844         /* check for control room outputs which may also interconnect Routes */
1845
1846         if (_control_outs) {
1847
1848                 no = _control_outs->n_outputs().get_total();
1849                 
1850                 for (i = 0; i < no; ++i) {
1851                         for (j = 0; j < ni; ++j) {
1852                                 if (_control_outs->output(i)->connected_to (other->input (j)->name())) {
1853                                         return true;
1854                                 }
1855                         }
1856                 }
1857         }
1858
1859         return false;
1860 }
1861
1862 void
1863 Route::set_mute_config (mute_type t, bool onoff, void *src)
1864 {
1865         switch (t) {
1866         case PRE_FADER:
1867                 _mute_affects_pre_fader = onoff;
1868                  pre_fader_changed(src); /* EMIT SIGNAL */
1869                 break;
1870
1871         case POST_FADER:
1872                 _mute_affects_post_fader = onoff;
1873                  post_fader_changed(src); /* EMIT SIGNAL */
1874                 break;
1875
1876         case CONTROL_OUTS:
1877                 _mute_affects_control_outs = onoff;
1878                  control_outs_changed(src); /* EMIT SIGNAL */
1879                 break;
1880
1881         case MAIN_OUTS:
1882                 _mute_affects_main_outs = onoff;
1883                  main_outs_changed(src); /* EMIT SIGNAL */
1884                 break;
1885         }
1886 }
1887
1888 bool
1889 Route::get_mute_config (mute_type t)
1890 {
1891         bool onoff = false;
1892         
1893         switch (t){
1894         case PRE_FADER:
1895                 onoff = _mute_affects_pre_fader; 
1896                 break;
1897         case POST_FADER:
1898                 onoff = _mute_affects_post_fader;
1899                 break;
1900         case CONTROL_OUTS:
1901                 onoff = _mute_affects_control_outs;
1902                 break;
1903         case MAIN_OUTS:
1904                 onoff = _mute_affects_main_outs;
1905                 break;
1906         }
1907         
1908         return onoff;
1909 }
1910
1911 void
1912 Route::set_active (bool yn)
1913 {
1914         _active = yn; 
1915          active_changed(); /* EMIT SIGNAL */
1916 }
1917
1918 void
1919 Route::handle_transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_redirects)
1920 {
1921         nframes_t now = _session.transport_frame();
1922
1923         {
1924                 Glib::RWLock::ReaderLock lm (redirect_lock);
1925
1926                 if (!did_locate) {
1927                         automation_snapshot (now);
1928                 }
1929
1930                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1931                         
1932                         if (Config->get_plugins_stop_with_transport() && can_flush_redirects) {
1933                                 (*i)->deactivate ();
1934                                 (*i)->activate ();
1935                         }
1936                         
1937                         (*i)->transport_stopped (now);
1938                 }
1939         }
1940
1941         IO::transport_stopped (now);
1942  
1943         _roll_delay = _initial_delay;
1944 }
1945
1946 void
1947 Route::input_change_handler (IOChange change, void *ignored)
1948 {
1949         if (change & ConfigurationChanged) {
1950                 reset_plugin_counts (0);
1951         }
1952 }
1953
1954 void
1955 Route::output_change_handler (IOChange change, void *ignored)
1956 {
1957         if (change & ConfigurationChanged) {
1958                 if (_control_outs) {
1959                         _control_outs->ensure_io (ChanCount::ZERO, ChanCount(DataType::AUDIO, n_outputs().get(DataType::AUDIO)), true, this);
1960                 }
1961                 
1962                 reset_plugin_counts (0);
1963         }
1964 }
1965
1966 uint32_t
1967 Route::pans_required () const
1968 {
1969         if (n_outputs().get(DataType::AUDIO) < 2) {
1970                 return 0;
1971         }
1972         
1973         return max (n_inputs ().get(DataType::AUDIO), static_cast<size_t>(redirect_max_outs.get(DataType::AUDIO)));
1974 }
1975
1976 int 
1977 Route::no_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
1978                    bool session_state_changing, bool can_record, bool rec_monitors_input)
1979 {
1980         if (n_outputs().get_total() == 0) {
1981                 return 0;
1982         }
1983
1984         if (session_state_changing || !_active)  {
1985                 silence (nframes, offset);
1986                 return 0;
1987         }
1988
1989         apply_gain_automation = false;
1990         
1991         if (n_inputs().get_total()) {
1992                 passthru (start_frame, end_frame, nframes, offset, 0, false);
1993         } else {
1994                 silence (nframes, offset);
1995         }
1996
1997         return 0;
1998 }
1999
2000 nframes_t
2001 Route::check_initial_delay (nframes_t nframes, nframes_t& offset, nframes_t& transport_frame)
2002 {
2003         if (_roll_delay > nframes) {
2004
2005                 _roll_delay -= nframes;
2006                 silence (nframes, offset);
2007                 /* transport frame is not legal for caller to use */
2008                 return 0;
2009
2010         } else if (_roll_delay > 0) {
2011
2012                 nframes -= _roll_delay;
2013
2014                 silence (_roll_delay, offset);
2015
2016                 offset += _roll_delay;
2017                 transport_frame += _roll_delay;
2018
2019                 _roll_delay = 0;
2020         }
2021
2022         return nframes;
2023 }
2024
2025 int
2026 Route::roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, int declick,
2027              bool can_record, bool rec_monitors_input)
2028 {
2029         {
2030                 Glib::RWLock::ReaderLock lm (redirect_lock, Glib::TRY_LOCK);
2031                 if (lm.locked()) {
2032                         // automation snapshot can also be called from the non-rt context
2033                         // and it uses the redirect list, so we take the lock out here
2034                         automation_snapshot (_session.transport_frame());
2035                 }
2036         }
2037
2038         if ((n_outputs().get_total() == 0 && _redirects.empty()) || n_inputs().get_total() == 0 || !_active) {
2039                 silence (nframes, offset);
2040                 return 0;
2041         }
2042         
2043         nframes_t unused = 0;
2044
2045         if ((nframes = check_initial_delay (nframes, offset, unused)) == 0) {
2046                 return 0;
2047         }
2048
2049         _silent = false;
2050
2051         apply_gain_automation = false;
2052
2053         { 
2054                 Glib::Mutex::Lock am (automation_lock, Glib::TRY_LOCK);
2055                 
2056                 if (am.locked() && _session.transport_rolling()) {
2057                         
2058                         if (gain_automation_playback()) {
2059                                 apply_gain_automation = _gain_automation_curve.rt_safe_get_vector (start_frame, end_frame, _session.gain_automation_buffer(), nframes);
2060                         }
2061                 }
2062         }
2063
2064         passthru (start_frame, end_frame, nframes, offset, declick, false);
2065
2066         return 0;
2067 }
2068
2069 int
2070 Route::silent_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
2071                     bool can_record, bool rec_monitors_input)
2072 {
2073         silence (nframes, offset);
2074         return 0;
2075 }
2076
2077 void
2078 Route::toggle_monitor_input ()
2079 {
2080         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2081                 i->ensure_monitor_input( ! i->monitoring_input());
2082         }
2083 }
2084
2085 bool
2086 Route::has_external_redirects () const
2087 {
2088         boost::shared_ptr<const PortInsert> pi;
2089         
2090         for (RedirectList::const_iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2091                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2092
2093                         for (PortSet::const_iterator port = pi->outputs().begin();
2094                                         port != pi->outputs().end(); ++port) {
2095                                 
2096                                 string port_name = port->name();
2097                                 string client_name = port_name.substr (0, port_name.find(':'));
2098
2099                                 /* only say "yes" if the redirect is actually in use */
2100                                 
2101                                 if (client_name != "ardour" && pi->active()) {
2102                                         return true;
2103                                 }
2104                         }
2105                 }
2106         }
2107
2108         return false;
2109 }
2110
2111 void
2112 Route::flush_redirects ()
2113 {
2114         /* XXX shouldn't really try to take this lock, since
2115            this is called from the RT audio thread.
2116         */
2117
2118         Glib::RWLock::ReaderLock lm (redirect_lock);
2119
2120         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2121                 (*i)->deactivate ();
2122                 (*i)->activate ();
2123         }
2124 }
2125
2126 void
2127 Route::set_meter_point (MeterPoint p, void *src)
2128 {
2129         if (_meter_point != p) {
2130                 _meter_point = p;
2131                  meter_change (src); /* EMIT SIGNAL */
2132                 _session.set_dirty ();
2133         }
2134 }
2135
2136 nframes_t
2137 Route::update_total_latency ()
2138 {
2139         _own_latency = 0;
2140
2141         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2142                 if ((*i)->active ()) {
2143                         _own_latency += (*i)->latency ();
2144                 }
2145         }
2146
2147         set_port_latency (_own_latency);
2148
2149         /* this (virtual) function is used for pure Routes,
2150            not derived classes like AudioTrack.  this means
2151            that the data processed here comes from an input
2152            port, not prerecorded material, and therefore we
2153            have to take into account any input latency.
2154         */
2155
2156         _own_latency += input_latency ();
2157
2158         return _own_latency;
2159 }
2160
2161 void
2162 Route::set_latency_delay (nframes_t longest_session_latency)
2163 {
2164         _initial_delay = longest_session_latency - _own_latency;
2165
2166         if (_session.transport_stopped()) {
2167                 _roll_delay = _initial_delay;
2168         }
2169 }
2170
2171 void
2172 Route::automation_snapshot (nframes_t now)
2173 {
2174         IO::automation_snapshot (now);
2175
2176         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2177                 (*i)->automation_snapshot (now);
2178         }
2179 }
2180
2181 Route::ToggleControllable::ToggleControllable (std::string name, Route& s, ToggleType tp)
2182         : Controllable (name), route (s), type(tp)
2183 {
2184         
2185 }
2186
2187 void
2188 Route::ToggleControllable::set_value (float val)
2189 {
2190         bool bval = ((val >= 0.5f) ? true: false);
2191         
2192         switch (type) {
2193         case MuteControl:
2194                 route.set_mute (bval, this);
2195                 break;
2196         case SoloControl:
2197                 route.set_solo (bval, this);
2198                 break;
2199         default:
2200                 break;
2201         }
2202 }
2203
2204 float
2205 Route::ToggleControllable::get_value (void) const
2206 {
2207         float val = 0.0f;
2208         
2209         switch (type) {
2210         case MuteControl:
2211                 val = route.muted() ? 1.0f : 0.0f;
2212                 break;
2213         case SoloControl:
2214                 val = route.soloed() ? 1.0f : 0.0f;
2215                 break;
2216         default:
2217                 break;
2218         }
2219
2220         return val;
2221 }
2222
2223 void 
2224 Route::set_block_size (nframes_t nframes)
2225 {
2226         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2227                 (*i)->set_block_size (nframes);
2228         }
2229 }
2230
2231 void
2232 Route::redirect_active_proxy (Redirect* ignored, void* ignored_src)
2233 {
2234         _session.update_latency_compensation (false, false);
2235 }
2236
2237 void
2238 Route::protect_automation ()
2239 {
2240         switch (gain_automation_state()) {
2241         case Write:
2242         case Touch:
2243                 set_gain_automation_state (Off);
2244                 break;
2245         default:
2246                 break;
2247         }
2248
2249         switch (panner().automation_state ()) {
2250         case Write:
2251         case Touch:
2252                 panner().set_automation_state (Off);
2253                 break;
2254         default:
2255                 break;
2256         }
2257         
2258         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2259                 boost::shared_ptr<PluginInsert> pi;
2260                 if ((pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2261                         pi->protect_automation ();
2262                 }
2263         }
2264 }
2265
2266 void
2267 Route::set_pending_declick (int declick)
2268 {
2269         if (_declickable) {
2270                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2271                 if (declick) {
2272                         _pending_declick = declick;
2273                 }
2274                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2275         } else {
2276                 _pending_declick = 0;
2277         }
2278
2279 }