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