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