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