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