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