Merge big changes (mostly Controllable) from trunk
[ardour.git] / libs / ardour / route.cc
1 /*
2     Copyright (C) 2000 Paul Davis 
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18     $Id$
19 */
20
21 #include <cmath>
22 #include <fstream>
23 #include <cassert>
24
25 #include <sigc++/bind.h>
26 #include <pbd/xml++.h>
27
28 #include <ardour/timestamps.h>
29 #include <ardour/audioengine.h>
30 #include <ardour/route.h>
31 #include <ardour/insert.h>
32 #include <ardour/send.h>
33 #include <ardour/session.h>
34 #include <ardour/utils.h>
35 #include <ardour/configuration.h>
36 #include <ardour/cycle_timer.h>
37 #include <ardour/route_group.h>
38 #include <ardour/port.h>
39 #include <ardour/ladspa_plugin.h>
40 #include <ardour/panner.h>
41 #include <ardour/dB.h>
42 #include <ardour/mix.h>
43
44 #include "i18n.h"
45
46 using namespace std;
47 using namespace ARDOUR;
48 using namespace PBD;
49
50
51 uint32_t Route::order_key_cnt = 0;
52
53
54 Route::Route (Session& sess, string name, int input_min, int input_max, int output_min, int output_max, Flag flg, Buffer::Type default_type)
55         : IO (sess, name, input_min, input_max, output_min, output_max, default_type),
56           _flags (flg),
57           _solo_control (*this, ToggleControllable::SoloControl),
58           _mute_control (*this, ToggleControllable::MuteControl)
59 {
60         init ();
61 }
62
63 Route::Route (Session& sess, const XMLNode& node)
64         : IO (sess, "route"),
65           _solo_control (*this, ToggleControllable::SoloControl),
66           _mute_control (*this, ToggleControllable::MuteControl)
67 {
68         init ();
69         set_state (node);
70 }
71
72 void
73 Route::init ()
74 {
75         redirect_max_outs = 0;
76         _muted = false;
77         _soloed = false;
78         _solo_safe = false;
79         _phase_invert = false;
80         order_keys[N_("signal")] = order_key_cnt++;
81         _active = true;
82         _silent = false;
83         _meter_point = MeterPostFader;
84         _initial_delay = 0;
85         _roll_delay = 0;
86         _own_latency = 0;
87         _have_internal_generator = false;
88         _declickable = false;
89         _pending_declick = true;
90         _remote_control_id = 0;
91
92         _edit_group = 0;
93         _mix_group = 0;
94
95         _mute_affects_pre_fader = Config->get_mute_affects_pre_fader();
96         _mute_affects_post_fader = Config->get_mute_affects_post_fader();
97         _mute_affects_control_outs = Config->get_mute_affects_control_outs();
98         _mute_affects_main_outs = Config->get_mute_affects_main_outs();
99         
100         solo_gain = 1.0;
101         desired_solo_gain = 1.0;
102         mute_gain = 1.0;
103         desired_mute_gain = 1.0;
104
105         _control_outs = 0;
106
107         input_changed.connect (mem_fun (this, &Route::input_change_handler));
108         output_changed.connect (mem_fun (this, &Route::output_change_handler));
109 }
110
111 Route::~Route ()
112 {
113         GoingAway (); /* EMIT SIGNAL */
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, _phase_invert);
266                 _pending_declick = 0;
267         } else if (declick < 0) {
268                 apply_declick (bufs, nbufs, nframes, 1.0, 0.0, _phase_invert);
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, _phase_invert);
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, _phase_invert);
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() && (!_session.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, _phase_invert);
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() && (!_session.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, _phase_invert);
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() && (!_session.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, _phase_invert);
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() && (!_session.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 && (_session.solo_model() != Session::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 (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                 PluginInsert* pi;
772                 PortInsert* porti;
773
774                 uint32_t potential_max_streams = 0;
775
776                 if ((pi = dynamic_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 = dynamic_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                         PluginInsert* pi;
852                         
853                         if ((pi = dynamic_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
903                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
904                         delete *i;
905                 }
906
907                 _redirects.clear ();
908         }
909
910         if (redirect_max_outs != old_rmo) {
911                 reset_panner ();
912         }
913         
914         redirect_max_outs = 0;
915         _have_internal_generator = false;
916         redirects_changed (src); /* EMIT SIGNAL */
917 }
918
919 int
920 Route::remove_redirect (Redirect *redirect, void *src, uint32_t* err_streams)
921 {
922         uint32_t old_rmo = redirect_max_outs;
923
924         if (!_session.engine().connected()) {
925                 return 1;
926         }
927
928         redirect_max_outs = 0;
929
930         {
931                 Glib::RWLock::WriterLock lm (redirect_lock);
932                 RedirectList::iterator i;
933                 bool removed = false;
934
935                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
936                         if (*i == redirect) {
937
938                                 RedirectList::iterator tmp;
939
940                                 /* move along, see failure case for reset_plugin_counts()
941                                    where we may need to reinsert the redirect.
942                                 */
943
944                                 tmp = i;
945                                 ++tmp;
946
947                                 /* stop redirects that send signals to JACK ports
948                                    from causing noise as a result of no longer being
949                                    run.
950                                 */
951
952                                 Send* send;
953                                 PortInsert* port_insert;
954                                 
955                                 if ((send = dynamic_cast<Send*> (*i)) != 0) {
956                                         send->disconnect_inputs (this);
957                                         send->disconnect_outputs (this);
958                                 } else if ((port_insert = dynamic_cast<PortInsert*> (*i)) != 0) {
959                                         port_insert->disconnect_inputs (this);
960                                         port_insert->disconnect_outputs (this);
961                                 }
962
963                                 _redirects.erase (i);
964
965                                 i = tmp;
966                                 removed = true;
967                                 break;
968                         }
969                 }
970
971                 if (!removed) {
972                         /* what? */
973                         return 1;
974                 }
975
976                 if (_reset_plugin_counts (err_streams)) {
977                         /* get back to where we where */
978                         _redirects.insert (i, redirect);
979                         /* we know this will work, because it worked before :) */
980                         _reset_plugin_counts (0);
981                         return -1;
982                 }
983
984                 bool foo = false;
985
986                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
987                         PluginInsert* pi;
988
989                         if ((pi = dynamic_cast<PluginInsert*>(*i)) != 0) {
990                                 if (pi->is_generator()) {
991                                         foo = true;
992                                 }
993                         }
994                 }
995
996                 _have_internal_generator = foo;
997         }
998
999         if (old_rmo != redirect_max_outs) {
1000                 reset_panner ();
1001         }
1002
1003         redirects_changed (src); /* EMIT SIGNAL */
1004         return 0;
1005 }
1006
1007 int
1008 Route::reset_plugin_counts (uint32_t* lpc)
1009 {
1010         Glib::RWLock::WriterLock lm (redirect_lock);
1011         return _reset_plugin_counts (lpc);
1012 }
1013
1014
1015 int
1016 Route::_reset_plugin_counts (uint32_t* err_streams)
1017 {
1018         RedirectList::iterator r;
1019         uint32_t i_cnt;
1020         uint32_t s_cnt;
1021         map<Placement,list<InsertCount> > insert_map;
1022         jack_nframes_t initial_streams;
1023
1024         redirect_max_outs = 0;
1025         i_cnt = 0;
1026         s_cnt = 0;
1027
1028         /* divide inserts up by placement so we get the signal flow
1029            properly modelled. we need to do this because the _redirects
1030            list is not sorted by placement, and because other reasons may 
1031            exist now or in the future for this separate treatment.
1032         */
1033         
1034         for (r = _redirects.begin(); r != _redirects.end(); ++r) {
1035
1036                 Insert *insert;
1037
1038                 /* do this here in case we bomb out before we get to the end of
1039                    this function.
1040                 */
1041
1042                 redirect_max_outs = max ((*r)->output_streams (), redirect_max_outs);
1043
1044                 if ((insert = dynamic_cast<Insert*>(*r)) != 0) {
1045                         ++i_cnt;
1046                         insert_map[insert->placement()].push_back (InsertCount (*insert));
1047
1048                         /* reset plugin counts back to one for now so
1049                            that we have a predictable, controlled
1050                            state to try to configure.
1051                         */
1052
1053                         PluginInsert* pi;
1054                 
1055                         if ((pi = dynamic_cast<PluginInsert*>(insert)) != 0) {
1056                                 pi->set_count (1);
1057                         }
1058
1059                 } else if (dynamic_cast<Send*> (*r) != 0) {
1060                         ++s_cnt;
1061                 }
1062         }
1063         
1064         if (i_cnt == 0) {
1065                 if (s_cnt) {
1066                         goto recompute;
1067                 } else {
1068                         return 0;
1069                 }
1070         }
1071
1072         /* Now process each placement in order, checking to see if we 
1073            can really do what has been requested.
1074         */
1075
1076         /* A: PreFader */
1077         
1078         if (check_some_plugin_counts (insert_map[PreFader], n_inputs (), err_streams)) {
1079                 return -1;
1080         }
1081
1082         /* figure out the streams that will feed into PreFader */
1083
1084         if (!insert_map[PreFader].empty()) {
1085                 InsertCount& ic (insert_map[PreFader].back());
1086                 initial_streams = ic.insert.compute_output_streams (ic.cnt);
1087         } else {
1088                 initial_streams = n_inputs ();
1089         }
1090
1091         /* B: PostFader */
1092
1093         if (check_some_plugin_counts (insert_map[PostFader], initial_streams, err_streams)) {
1094                 return -1;
1095         }
1096
1097         /* OK, everything can be set up correctly, so lets do it */
1098
1099         apply_some_plugin_counts (insert_map[PreFader]);
1100         apply_some_plugin_counts (insert_map[PostFader]);
1101
1102         /* recompute max outs of any redirect */
1103
1104   recompute:
1105
1106         redirect_max_outs = 0;
1107         RedirectList::iterator prev = _redirects.end();
1108
1109         for (r = _redirects.begin(); r != _redirects.end(); prev = r, ++r) {
1110                 Send* s;
1111
1112                 if ((s = dynamic_cast<Send*> (*r)) != 0) {
1113                         if (r == _redirects.begin()) {
1114                                 s->expect_inputs (n_inputs());
1115                         } else {
1116                                 s->expect_inputs ((*prev)->output_streams());
1117                         }
1118                 }
1119
1120                 redirect_max_outs = max ((*r)->output_streams (), redirect_max_outs);
1121         }
1122
1123         /* we're done */
1124
1125         return 0;
1126 }                                  
1127
1128 int32_t
1129 Route::apply_some_plugin_counts (list<InsertCount>& iclist)
1130 {
1131         list<InsertCount>::iterator i;
1132
1133         for (i = iclist.begin(); i != iclist.end(); ++i) {
1134                 
1135                 if ((*i).insert.configure_io ((*i).cnt, (*i).in, (*i).out)) {
1136                         return -1;
1137                 }
1138                 /* make sure that however many we have, they are all active */
1139                 (*i).insert.activate ();
1140         }
1141
1142         return 0;
1143 }
1144
1145 int32_t
1146 Route::check_some_plugin_counts (list<InsertCount>& iclist, int32_t required_inputs, uint32_t* err_streams)
1147 {
1148         list<InsertCount>::iterator i;
1149         
1150         for (i = iclist.begin(); i != iclist.end(); ++i) {
1151
1152                 if (((*i).cnt = (*i).insert.can_support_input_configuration (required_inputs)) < 0) {
1153                         if (err_streams) {
1154                                 *err_streams = required_inputs;
1155                         }
1156                         return -1;
1157                 }
1158                 
1159                 (*i).in = required_inputs;
1160                 (*i).out = (*i).insert.compute_output_streams ((*i).cnt);
1161
1162                 required_inputs = (*i).out;
1163         }
1164
1165         return 0;
1166 }
1167
1168 int
1169 Route::copy_redirects (const Route& other, Placement placement, uint32_t* err_streams)
1170 {
1171         uint32_t old_rmo = redirect_max_outs;
1172
1173         if (err_streams) {
1174                 *err_streams = 0;
1175         }
1176
1177         RedirectList to_be_deleted;
1178
1179         {
1180                 Glib::RWLock::WriterLock lm (redirect_lock);
1181                 RedirectList::iterator tmp;
1182                 RedirectList the_copy;
1183
1184                 the_copy = _redirects;
1185                 
1186                 /* remove all relevant redirects */
1187
1188                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1189                         tmp = i;
1190                         ++tmp;
1191
1192                         if ((*i)->placement() == placement) {
1193                                 to_be_deleted.push_back (*i);
1194                                 _redirects.erase (i);
1195                         }
1196
1197                         i = tmp;
1198                 }
1199
1200                 /* now copy the relevant ones from "other" */
1201                 
1202                 for (RedirectList::const_iterator i = other._redirects.begin(); i != other._redirects.end(); ++i) {
1203                         if ((*i)->placement() == placement) {
1204                                 _redirects.push_back (Redirect::clone (**i));
1205                         }
1206                 }
1207
1208                 /* reset plugin stream handling */
1209
1210                 if (_reset_plugin_counts (err_streams)) {
1211
1212                         /* FAILED COPY ATTEMPT: we have to restore order */
1213
1214                         /* delete all cloned redirects */
1215
1216                         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1217
1218                                 tmp = i;
1219                                 ++tmp;
1220
1221                                 if ((*i)->placement() == placement) {
1222                                         delete *i;
1223                                         _redirects.erase (i);
1224                                 }
1225                                 
1226                                 i = tmp;
1227                         }
1228
1229                         /* restore the natural order */
1230
1231                         _redirects = the_copy;
1232                         redirect_max_outs = old_rmo;
1233
1234                         /* we failed, even though things are OK again */
1235
1236                         return -1;
1237
1238                 } else {
1239                         
1240                         /* SUCCESSFUL COPY ATTEMPT: delete the redirects we removed pre-copy */
1241
1242                         for (RedirectList::iterator i = to_be_deleted.begin(); i != to_be_deleted.end(); ++i) {
1243                                 delete *i;
1244                         }
1245                 }
1246         }
1247
1248         if (redirect_max_outs != old_rmo || old_rmo == 0) {
1249                 reset_panner ();
1250         }
1251
1252         redirects_changed (this); /* EMIT SIGNAL */
1253         return 0;
1254 }
1255
1256 void
1257 Route::all_redirects_flip ()
1258 {
1259         Glib::RWLock::ReaderLock lm (redirect_lock);
1260
1261         if (_redirects.empty()) {
1262                 return;
1263         }
1264
1265         bool first_is_on = _redirects.front()->active();
1266         
1267         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1268                 (*i)->set_active (!first_is_on, this);
1269         }
1270 }
1271
1272 void
1273 Route::all_redirects_active (bool state)
1274 {
1275         Glib::RWLock::ReaderLock lm (redirect_lock);
1276
1277         if (_redirects.empty()) {
1278                 return;
1279         }
1280
1281         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1282                 (*i)->set_active (state, this);
1283         }
1284 }
1285
1286 struct RedirectSorter {
1287     bool operator() (const Redirect *a, const Redirect *b) {
1288             return a->sort_key() < b->sort_key();
1289     }
1290 };
1291
1292 int
1293 Route::sort_redirects (uint32_t* err_streams)
1294 {
1295         {
1296                 RedirectSorter comparator;
1297                 Glib::RWLock::WriterLock lm (redirect_lock);
1298                 uint32_t old_rmo = redirect_max_outs;
1299
1300                 /* the sweet power of C++ ... */
1301
1302                 RedirectList as_it_was_before = _redirects;
1303
1304                 _redirects.sort (comparator);
1305         
1306                 if (_reset_plugin_counts (err_streams)) {
1307                         _redirects = as_it_was_before;
1308                         redirect_max_outs = old_rmo;
1309                         return -1;
1310                 } 
1311         } 
1312
1313         reset_panner ();
1314         redirects_changed (this); /* EMIT SIGNAL */
1315
1316         return 0;
1317 }
1318
1319 XMLNode&
1320 Route::get_state()
1321 {
1322         return state(true);
1323 }
1324
1325 XMLNode&
1326 Route::get_template()
1327 {
1328         return state(false);
1329 }
1330
1331 XMLNode&
1332 Route::state(bool full_state)
1333 {
1334         XMLNode *node = new XMLNode("Route");
1335         XMLNode *aevents;
1336         RedirectList:: iterator i;
1337         char buf[32];
1338
1339         if (_flags) {
1340                 snprintf (buf, sizeof (buf), "0x%x", _flags);
1341                 node->add_property("flags", buf);
1342         }
1343         
1344         // FIXME: assumes there's only audio and MIDI types
1345         node->add_property("default-type", Buffer::type_to_string(_default_type));
1346
1347         node->add_property("active", _active?"yes":"no");
1348         node->add_property("muted", _muted?"yes":"no");
1349         node->add_property("soloed", _soloed?"yes":"no");
1350         node->add_property("phase-invert", _phase_invert?"yes":"no");
1351         node->add_property("mute-affects-pre-fader", _mute_affects_pre_fader?"yes":"no"); 
1352         node->add_property("mute-affects-post-fader", _mute_affects_post_fader?"yes":"no"); 
1353         node->add_property("mute-affects-control-outs", _mute_affects_control_outs?"yes":"no"); 
1354         node->add_property("mute-affects-main-outs", _mute_affects_main_outs?"yes":"no"); 
1355
1356         if (_edit_group) {
1357                 node->add_property("edit-group", _edit_group->name());
1358         }
1359         if (_mix_group) {
1360                 node->add_property("mix-group", _mix_group->name());
1361         }
1362
1363         string order_string;
1364         OrderKeys::iterator x = order_keys.begin(); 
1365
1366         while (x != order_keys.end()) {
1367                 order_string += (*x).first;
1368                 order_string += '=';
1369                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1370                 order_string += buf;
1371                 
1372                 ++x;
1373
1374                 if (x == order_keys.end()) {
1375                         break;
1376                 }
1377
1378                 order_string += ':';
1379         }
1380         node->add_property ("order-keys", order_string);
1381
1382         node->add_child_nocopy (IO::state (full_state));
1383
1384         if (_control_outs) {
1385                 XMLNode* cnode = new XMLNode (X_("ControlOuts"));
1386                 cnode->add_child_nocopy (_control_outs->state (full_state));
1387                 node->add_child_nocopy (*cnode);
1388         }
1389
1390         if (_comment.length()) {
1391                 XMLNode *cmt = node->add_child ("Comment");
1392                 cmt->add_content (_comment);
1393         }
1394
1395         if (full_state) {
1396                 string path;
1397
1398                 path = _session.snap_name();
1399                 path += "-gain-";
1400                 path += legalize_for_path (_name);
1401                 path += ".automation";
1402
1403                 /* XXX we didn't ask for a state save, we asked for the current state.
1404                    FIX ME!
1405                 */
1406
1407                 if (save_automation (path)) {
1408                         error << _("Could not get state of route.  Problem with save_automation") << endmsg;
1409                 }
1410
1411                 aevents = node->add_child ("Automation");
1412                 aevents->add_property ("path", path);
1413         }       
1414
1415         for (i = _redirects.begin(); i != _redirects.end(); ++i) {
1416                 node->add_child_nocopy((*i)->state (full_state));
1417         }
1418
1419         if (_extra_xml){
1420                 node->add_child_copy (*_extra_xml);
1421         }
1422         
1423         return *node;
1424 }
1425
1426 void
1427 Route::set_deferred_state ()
1428 {
1429         XMLNodeList nlist;
1430         XMLNodeConstIterator niter;
1431
1432         if (!deferred_state) {
1433                 return;
1434         }
1435
1436         nlist = deferred_state->children();
1437
1438         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1439                 add_redirect_from_xml (**niter);
1440         }
1441
1442         delete deferred_state;
1443         deferred_state = 0;
1444 }
1445
1446 void
1447 Route::add_redirect_from_xml (const XMLNode& node)
1448 {
1449         const XMLProperty *prop;
1450         Insert *insert = 0;
1451         Send *send = 0;
1452
1453         if (node.name() == "Send") {
1454                 
1455                 try {
1456                         send = new Send (_session, node);
1457                 } 
1458                 
1459                 catch (failed_constructor &err) {
1460                         error << _("Send construction failed") << endmsg;
1461                         return;
1462                 }
1463                 
1464                 add_redirect (send, this);
1465                 
1466         } else if (node.name() == "Insert") {
1467                 
1468                 try {
1469                         if ((prop = node.property ("type")) != 0) {
1470
1471                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || prop->value() == "vst") {
1472
1473                                         insert = new PluginInsert(_session, node);
1474                                         
1475                                 } else if (prop->value() == "port") {
1476
1477
1478                                         insert = new PortInsert (_session, node);
1479
1480                                 } else {
1481
1482                                         error << string_compose(_("unknown Insert type \"%1\"; ignored"), prop->value()) << endmsg;
1483                                 }
1484
1485                                 add_redirect (insert, this);
1486                                 
1487                         } else {
1488                                 error << _("Insert XML node has no type property") << endmsg;
1489                         }
1490                 }
1491                 
1492                 catch (failed_constructor &err) {
1493                         warning << _("insert could not be created. Ignored.") << endmsg;
1494                         return;
1495                 }
1496         }
1497 }
1498
1499 int
1500 Route::set_state (const XMLNode& node)
1501 {
1502         XMLNodeList nlist;
1503         XMLNodeConstIterator niter;
1504         XMLNode *child;
1505         XMLPropertyList plist;
1506         const XMLProperty *prop;
1507
1508         if (node.name() != "Route"){
1509                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1510                 return -1;
1511         }
1512
1513         if ((prop = node.property ("flags")) != 0) {
1514                 int x;
1515                 sscanf (prop->value().c_str(), "0x%x", &x);
1516                 _flags = Flag (x);
1517         } else {
1518                 _flags = Flag (0);
1519         }
1520         
1521         if ((prop = node.property ("default-type")) != 0) {
1522                 _default_type = Buffer::type_from_string(prop->value());
1523                 assert(_default_type != Buffer::NIL);
1524         }
1525
1526         if ((prop = node.property ("phase-invert")) != 0) {
1527                 set_phase_invert(prop->value()=="yes"?true:false, this);
1528         }
1529
1530         if ((prop = node.property ("active")) != 0) {
1531                 set_active (prop->value() == "yes");
1532         }
1533
1534         if ((prop = node.property ("muted")) != 0) {
1535                 bool yn = prop->value()=="yes"?true:false; 
1536
1537                 /* force reset of mute status */
1538
1539                 _muted = !yn;
1540                 set_mute(yn, this);
1541                 mute_gain = desired_mute_gain;
1542         }
1543
1544         if ((prop = node.property ("soloed")) != 0) {
1545                 bool yn = prop->value()=="yes"?true:false; 
1546
1547                 /* force reset of solo status */
1548
1549                 _soloed = !yn;
1550                 set_solo (yn, this);
1551                 solo_gain = desired_solo_gain;
1552         }
1553
1554         if ((prop = node.property ("mute-affects-pre-fader")) != 0) {
1555                 _mute_affects_pre_fader = (prop->value()=="yes")?true:false;
1556         }
1557
1558         if ((prop = node.property ("mute-affects-post-fader")) != 0) {
1559                 _mute_affects_post_fader = (prop->value()=="yes")?true:false;
1560         }
1561
1562         if ((prop = node.property ("mute-affects-control-outs")) != 0) {
1563                 _mute_affects_control_outs = (prop->value()=="yes")?true:false;
1564         }
1565
1566         if ((prop = node.property ("mute-affects-main-outs")) != 0) {
1567                 _mute_affects_main_outs = (prop->value()=="yes")?true:false;
1568         }
1569
1570         if ((prop = node.property ("edit-group")) != 0) {
1571                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
1572                 if(edit_group == 0) {
1573                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1574                 } else {
1575                         set_edit_group(edit_group, this);
1576                 }
1577         }
1578
1579         if ((prop = node.property ("order-keys")) != 0) {
1580
1581                 long n;
1582
1583                 string::size_type colon, equal;
1584                 string remaining = prop->value();
1585
1586                 while (remaining.length()) {
1587
1588                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1589                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1590                                       << endmsg;
1591                         } else {
1592                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1593                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1594                                               << endmsg;
1595                                 } else {
1596                                         set_order_key (remaining.substr (0, equal), n);
1597                                 }
1598                         }
1599
1600                         colon = remaining.find_first_of (':');
1601
1602                         if (colon != string::npos) {
1603                                 remaining = remaining.substr (colon+1);
1604                         } else {
1605                                 break;
1606                         }
1607                 }
1608         }
1609
1610         nlist = node.children();
1611
1612         if (deferred_state) {
1613                 delete deferred_state;
1614         }
1615
1616         deferred_state = new XMLNode("deferred state");
1617
1618         /* set parent class properties before anything else */
1619
1620         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1621
1622                 child = *niter;
1623
1624                 if (child->name() == IO::state_node_name) {
1625
1626                         IO::set_state (*child);
1627                         break;
1628                 }
1629         }
1630                         
1631         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1632
1633                 child = *niter;
1634                         
1635                 if (child->name() == "Send") {
1636
1637
1638                         if (!IO::ports_legal) {
1639
1640                                 deferred_state->add_child_copy (*child);
1641
1642                         } else {
1643                                 add_redirect_from_xml (*child);
1644                         }
1645
1646                 } else if (child->name() == "Insert") {
1647                         
1648                         if (!IO::ports_legal) {
1649                                 
1650                                 deferred_state->add_child_copy (*child);
1651
1652                         } else {
1653                                 
1654                                 add_redirect_from_xml (*child);
1655                         }
1656
1657                 } else if (child->name() == "Automation") {
1658
1659                         XMLPropertyList plist;
1660                         XMLPropertyConstIterator piter;
1661                         XMLProperty *prop;
1662                         
1663                         plist = child->properties();
1664                         for (piter = plist.begin(); piter != plist.end(); ++piter) {
1665                                 prop = *piter;
1666                                 if (prop->name() == "path") {
1667                                         load_automation (prop->value());
1668                                 }
1669                         }
1670
1671                 } else if (child->name() == "ControlOuts") {
1672                         
1673                         string coutname = _name;
1674                         coutname += _("[control]");
1675
1676                         _control_outs = new IO (_session, coutname);
1677                         _control_outs->set_state (**(child->children().begin()));
1678
1679                 } else if (child->name() == "Comment") {
1680
1681                         /* XXX this is a terrible API design in libxml++ */
1682
1683                         XMLNode *cmt = *(child->children().begin());
1684                         _comment = cmt->content();
1685
1686                 } else if (child->name() == "extra") {
1687                         _extra_xml = new XMLNode (*child);
1688                 }
1689         }
1690
1691         if ((prop = node.property ("mix-group")) != 0) {
1692                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
1693                 if (mix_group == 0) {
1694                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1695                 }  else {
1696                         set_mix_group(mix_group, this);
1697                 }
1698         }
1699
1700         return 0;
1701 }
1702
1703 void
1704 Route::curve_reallocate ()
1705 {
1706 //      _gain_automation_curve.finish_resize ();
1707 //      _pan_automation_curve.finish_resize ();
1708 }
1709
1710 void
1711 Route::silence (jack_nframes_t nframes, jack_nframes_t offset)
1712 {
1713         if (!_silent) {
1714
1715                 // reset_peak_meters ();
1716                 
1717                 IO::silence (nframes, offset);
1718
1719                 if (_control_outs) {
1720                         _control_outs->silence (nframes, offset);
1721                 }
1722
1723                 { 
1724                         Glib::RWLock::ReaderLock lm (redirect_lock, Glib::TRY_LOCK);
1725                         
1726                         if (lm.locked()) {
1727                                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1728                                         PluginInsert* pi;
1729                                         if (!_active && (pi = dynamic_cast<PluginInsert*> (*i)) != 0) {
1730                                                 // skip plugins, they don't need anything when we're not active
1731                                                 continue;
1732                                         }
1733
1734                                         (*i)->silence (nframes, offset);
1735                                 }
1736
1737                                 if (nframes == _session.get_block_size() && offset == 0) {
1738                                         // _silent = true;
1739                                 }
1740                         }
1741                 }
1742                 
1743         }
1744 }       
1745
1746 int
1747 Route::set_control_outs (const vector<string>& ports)
1748 {
1749         Glib::Mutex::Lock lm (control_outs_lock);
1750         vector<string>::const_iterator i;
1751
1752         if (_control_outs) {
1753                 delete _control_outs;
1754                 _control_outs = 0;
1755         }
1756         
1757         if (ports.empty()) {
1758                 return 0;
1759         }
1760  
1761         string coutname = _name;
1762         coutname += _("[control]");
1763         
1764         _control_outs = new IO (_session, coutname);
1765
1766         /* our control outs need as many outputs as we
1767            have outputs. we track the changes in ::output_change_handler().
1768         */
1769
1770         _control_outs->ensure_io (0, n_outputs(), true, this);
1771  
1772         return 0;
1773 }       
1774
1775 void
1776 Route::set_edit_group (RouteGroup *eg, void *src)
1777
1778 {
1779         if (eg == _edit_group) {
1780                 return;
1781         }
1782
1783         if (_edit_group) {
1784                 _edit_group->remove (this);
1785         }
1786
1787         if ((_edit_group = eg) != 0) {
1788                 _edit_group->add (this);
1789         }
1790
1791         _session.set_dirty ();
1792         edit_group_changed (src); /* EMIT SIGNAL */
1793 }
1794
1795 void
1796 Route::drop_edit_group (void *src)
1797 {
1798         _edit_group = 0;
1799         _session.set_dirty ();
1800         edit_group_changed (src); /* EMIT SIGNAL */
1801 }
1802
1803 void
1804 Route::set_mix_group (RouteGroup *mg, void *src)
1805
1806 {
1807         if (mg == _mix_group) {
1808                 return;
1809         }
1810
1811         if (_mix_group) {
1812                 _mix_group->remove (this);
1813         }
1814
1815         if ((_mix_group = mg) != 0) {
1816                 _mix_group->add (this);
1817         }
1818
1819         _session.set_dirty ();
1820         mix_group_changed (src); /* EMIT SIGNAL */
1821 }
1822
1823 void
1824 Route::drop_mix_group (void *src)
1825 {
1826         _mix_group = 0;
1827         _session.set_dirty ();
1828         mix_group_changed (src); /* EMIT SIGNAL */
1829 }
1830
1831 void
1832 Route::set_comment (string cmt, void *src)
1833 {
1834         _comment = cmt;
1835         comment_changed (src);
1836         _session.set_dirty ();
1837 }
1838
1839 bool
1840 Route::feeds (Route *o)
1841 {
1842         uint32_t i, j;
1843
1844         IO& other = *o;
1845         IO& self = *this;
1846         uint32_t no = self.n_outputs();
1847         uint32_t ni = other.n_inputs ();
1848
1849         for (i = 0; i < no; ++i) {
1850                 for (j = 0; j < ni; ++j) {
1851                         if (self.output(i)->connected_to (other.input(j)->name())) {
1852                                 return true;
1853                         }
1854                 }
1855         }
1856
1857         /* check Redirects which may also interconnect Routes */
1858
1859         for (RedirectList::iterator r = _redirects.begin(); r != _redirects.end(); r++) {
1860
1861                 no = (*r)->n_outputs();
1862
1863                 for (i = 0; i < no; ++i) {
1864                         for (j = 0; j < ni; ++j) {
1865                                 if ((*r)->output(i)->connected_to (other.input (j)->name())) {
1866                                         return true;
1867                                 }
1868                         }
1869                 }
1870         }
1871
1872         /* check for control room outputs which may also interconnect Routes */
1873
1874         if (_control_outs) {
1875
1876                 no = _control_outs->n_outputs();
1877                 
1878                 for (i = 0; i < no; ++i) {
1879                         for (j = 0; j < ni; ++j) {
1880                                 if (_control_outs->output(i)->connected_to (other.input (j)->name())) {
1881                                         return true;
1882                                 }
1883                         }
1884                 }
1885         }
1886
1887         return false;
1888 }
1889
1890 void
1891 Route::set_mute_config (mute_type t, bool onoff, void *src)
1892 {
1893         switch (t) {
1894         case PRE_FADER:
1895                 _mute_affects_pre_fader = onoff;
1896                  pre_fader_changed(src); /* EMIT SIGNAL */
1897                 break;
1898
1899         case POST_FADER:
1900                 _mute_affects_post_fader = onoff;
1901                  post_fader_changed(src); /* EMIT SIGNAL */
1902                 break;
1903
1904         case CONTROL_OUTS:
1905                 _mute_affects_control_outs = onoff;
1906                  control_outs_changed(src); /* EMIT SIGNAL */
1907                 break;
1908
1909         case MAIN_OUTS:
1910                 _mute_affects_main_outs = onoff;
1911                  main_outs_changed(src); /* EMIT SIGNAL */
1912                 break;
1913         }
1914 }
1915
1916 bool
1917 Route::get_mute_config (mute_type t)
1918 {
1919         bool onoff = false;
1920         
1921         switch (t){
1922         case PRE_FADER:
1923                 onoff = _mute_affects_pre_fader; 
1924                 break;
1925         case POST_FADER:
1926                 onoff = _mute_affects_post_fader;
1927                 break;
1928         case CONTROL_OUTS:
1929                 onoff = _mute_affects_control_outs;
1930                 break;
1931         case MAIN_OUTS:
1932                 onoff = _mute_affects_main_outs;
1933                 break;
1934         }
1935         
1936         return onoff;
1937 }
1938
1939 void
1940 Route::set_active (bool yn)
1941 {
1942         _active = yn; 
1943          active_changed(); /* EMIT SIGNAL */
1944 }
1945
1946 void
1947 Route::handle_transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_redirects)
1948 {
1949         jack_nframes_t now = _session.transport_frame();
1950
1951         {
1952                 Glib::RWLock::ReaderLock lm (redirect_lock);
1953
1954                 if (!did_locate) {
1955                         automation_snapshot (now);
1956                 }
1957
1958                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1959                         
1960                         if (Config->get_plugins_stop_with_transport() && can_flush_redirects) {
1961                                 (*i)->deactivate ();
1962                                 (*i)->activate ();
1963                         }
1964                         
1965                         (*i)->transport_stopped (now);
1966                 }
1967         }
1968
1969         IO::transport_stopped (now);
1970  
1971         _roll_delay = _initial_delay;
1972 }
1973
1974 UndoAction
1975 Route::get_memento() const
1976 {
1977         void (Route::*pmf)(state_id_t) = &Route::set_state;
1978         return sigc::bind (mem_fun (*(const_cast<Route *>(this)), pmf), _current_state_id);
1979 }
1980
1981 void
1982 Route::set_state (state_id_t id)
1983 {
1984         return;
1985 }
1986
1987 void
1988 Route::input_change_handler (IOChange change, void *ignored)
1989 {
1990         if (change & ConfigurationChanged) {
1991                 reset_plugin_counts (0);
1992         }
1993 }
1994
1995 void
1996 Route::output_change_handler (IOChange change, void *ignored)
1997 {
1998         if (change & ConfigurationChanged) {
1999                 if (_control_outs) {
2000                         _control_outs->ensure_io (0, n_outputs(), true, this);
2001                 }
2002                 
2003                 reset_plugin_counts (0);
2004         }
2005 }
2006
2007 uint32_t
2008 Route::pans_required () const
2009 {
2010         if (n_outputs() < 2) {
2011                 return 0;
2012         }
2013         
2014         return max (n_inputs (), redirect_max_outs);
2015 }
2016
2017 int 
2018 Route::no_roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, 
2019                    bool session_state_changing, bool can_record, bool rec_monitors_input)
2020 {
2021         if (n_outputs() == 0) {
2022                 return 0;
2023         }
2024
2025         if (session_state_changing || !_active)  {
2026                 silence (nframes, offset);
2027                 return 0;
2028         }
2029
2030         apply_gain_automation = false;
2031         
2032         if (n_inputs()) {
2033                 passthru (start_frame, end_frame, nframes, offset, 0, false);
2034         } else {
2035                 silence (nframes, offset);
2036         }
2037
2038         return 0;
2039 }
2040
2041 jack_nframes_t
2042 Route::check_initial_delay (jack_nframes_t nframes, jack_nframes_t& offset, jack_nframes_t& transport_frame)
2043 {
2044         if (_roll_delay > nframes) {
2045
2046                 _roll_delay -= nframes;
2047                 silence (nframes, offset);
2048                 /* transport frame is not legal for caller to use */
2049                 return 0;
2050
2051         } else if (_roll_delay > 0) {
2052
2053                 nframes -= _roll_delay;
2054
2055                 silence (_roll_delay, offset);
2056
2057                 offset += _roll_delay;
2058                 transport_frame += _roll_delay;
2059
2060                 _roll_delay = 0;
2061         }
2062
2063         return nframes;
2064 }
2065
2066 int
2067 Route::roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, int declick,
2068              bool can_record, bool rec_monitors_input)
2069 {
2070         {
2071                 Glib::RWLock::ReaderLock lm (redirect_lock, Glib::TRY_LOCK);
2072                 if (lm.locked()) {
2073                         // automation snapshot can also be called from the non-rt context
2074                         // and it uses the redirect list, so we take the lock out here
2075                         automation_snapshot (_session.transport_frame());
2076                 }
2077         }
2078                 
2079         if ((n_outputs() == 0 && _redirects.empty()) || n_inputs() == 0 || !_active) {
2080                 silence (nframes, offset);
2081                 return 0;
2082         }
2083         
2084         jack_nframes_t unused = 0;
2085
2086         if ((nframes = check_initial_delay (nframes, offset, unused)) == 0) {
2087                 return 0;
2088         }
2089
2090         _silent = false;
2091
2092         apply_gain_automation = false;
2093
2094         { 
2095                 Glib::Mutex::Lock am (automation_lock, Glib::TRY_LOCK);
2096                 
2097                 if (am.locked() && _session.transport_rolling()) {
2098                         
2099                         jack_nframes_t start_frame = end_frame - nframes;
2100                         
2101                         if (gain_automation_playback()) {
2102                                 apply_gain_automation = _gain_automation_curve.rt_safe_get_vector (start_frame, end_frame, _session.gain_automation_buffer(), nframes);
2103                         }
2104                 }
2105         }
2106
2107         passthru (start_frame, end_frame, nframes, offset, declick, false);
2108
2109         return 0;
2110 }
2111
2112 int
2113 Route::silent_roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, 
2114                     bool can_record, bool rec_monitors_input)
2115 {
2116         silence (nframes, offset);
2117         return 0;
2118 }
2119
2120 void
2121 Route::toggle_monitor_input ()
2122 {
2123         for (vector<Port*>::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2124                 (*i)->request_monitor_input(!(*i)->monitoring_input());
2125         }
2126 }
2127
2128 bool
2129 Route::has_external_redirects () const
2130 {
2131         const PortInsert* pi;
2132         
2133         for (RedirectList::const_iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2134                 if ((pi = dynamic_cast<const PortInsert*>(*i)) != 0) {
2135
2136                         uint32_t no = pi->n_outputs();
2137
2138                         for (uint32_t n = 0; n < no; ++n) {
2139                                 
2140                                 string port_name = pi->output(n)->name();
2141                                 string client_name = port_name.substr (0, port_name.find(':'));
2142
2143                                 /* only say "yes" if the redirect is actually in use */
2144                                 
2145                                 if (client_name != "ardour" && pi->active()) {
2146                                         return true;
2147                                 }
2148                         }
2149                 }
2150         }
2151
2152         return false;
2153 }
2154
2155 void
2156 Route::flush_redirects ()
2157 {
2158         /* XXX shouldn't really try to take this lock, since
2159            this is called from the RT audio thread.
2160         */
2161
2162         Glib::RWLock::ReaderLock lm (redirect_lock);
2163
2164         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2165                 (*i)->deactivate ();
2166                 (*i)->activate ();
2167         }
2168 }
2169
2170 void
2171 Route::set_meter_point (MeterPoint p, void *src)
2172 {
2173         if (_meter_point != p) {
2174                 _meter_point = p;
2175                  meter_change (src); /* EMIT SIGNAL */
2176                 _session.set_dirty ();
2177         }
2178 }
2179
2180 jack_nframes_t
2181 Route::update_total_latency ()
2182 {
2183         _own_latency = 0;
2184
2185         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2186                 if ((*i)->active ()) {
2187                         _own_latency += (*i)->latency ();
2188                 }
2189         }
2190
2191         set_port_latency (_own_latency);
2192
2193         /* this (virtual) function is used for pure Routes,
2194            not derived classes like AudioTrack.  this means
2195            that the data processed here comes from an input
2196            port, not prerecorded material, and therefore we
2197            have to take into account any input latency.
2198         */
2199
2200         _own_latency += input_latency ();
2201
2202         return _own_latency;
2203 }
2204
2205 void
2206 Route::set_latency_delay (jack_nframes_t longest_session_latency)
2207 {
2208         _initial_delay = longest_session_latency - _own_latency;
2209
2210         if (_session.transport_stopped()) {
2211                 _roll_delay = _initial_delay;
2212         }
2213 }
2214
2215 void
2216 Route::automation_snapshot (jack_nframes_t now)
2217 {
2218         IO::automation_snapshot (now);
2219
2220         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2221                 (*i)->automation_snapshot (now);
2222         }
2223 }
2224
2225 Route::ToggleControllable::ToggleControllable (Route& s, ToggleType tp)
2226         : route (s), type(tp)
2227 {
2228         
2229 }
2230
2231 void
2232 Route::ToggleControllable::set_value (float val)
2233 {
2234         bool bval = ((val >= 0.5f) ? true: false);
2235         
2236         switch (type) {
2237         case MuteControl:
2238                 route.set_mute (bval, this);
2239                 break;
2240         case SoloControl:
2241                 route.set_solo (bval, this);
2242                 break;
2243         default:
2244                 break;
2245         }
2246 }
2247
2248 float
2249 Route::ToggleControllable::get_value (void) const
2250 {
2251         float val = 0.0f;
2252         
2253         switch (type) {
2254         case MuteControl:
2255                 val = route.muted() ? 1.0f : 0.0f;
2256                 break;
2257         case SoloControl:
2258                 val = route.soloed() ? 1.0f : 0.0f;
2259                 break;
2260         default:
2261                 break;
2262         }
2263
2264         return val;
2265 }
2266
2267 void 
2268 Route::set_block_size (jack_nframes_t nframes)
2269 {
2270         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2271                 (*i)->set_block_size (nframes);
2272         }
2273 }
2274
2275 void
2276 Route::redirect_active_proxy (Redirect* ignored, void* ignored_src)
2277 {
2278         _session.update_latency_compensation (false, false);
2279 }
2280
2281 void
2282 Route::protect_automation ()
2283 {
2284         switch (gain_automation_state()) {
2285         case Write:
2286         case Touch:
2287                 set_gain_automation_state (Off);
2288                 break;
2289         default:
2290                 break;
2291         }
2292
2293         switch (panner().automation_state ()) {
2294         case Write:
2295         case Touch:
2296                 panner().set_automation_state (Off);
2297                 break;
2298         default:
2299                 break;
2300         }
2301         
2302         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2303                 PluginInsert* pi;
2304                 if ((pi = dynamic_cast<PluginInsert*> (*i)) != 0) {
2305                         pi->protect_automation ();
2306                 }
2307         }
2308 }
2309
2310 void
2311 Route::set_pending_declick (int declick)
2312 {
2313         if (_declickable) {
2314                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2315                 if (declick) {
2316                         _pending_declick = declick;
2317                 }
2318                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2319         } else {
2320                 _pending_declick = 0;
2321         }
2322
2323 }