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