ignore send output counts when computing effect of redirects on route stream count
[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                 } else {
1152                         
1153                         /* don't pay any attention to send output configuration, since it doesn't
1154                            affect the route.
1155                          */
1156
1157                         redirect_max_outs = max ((*r)->output_streams (), redirect_max_outs);
1158                         
1159                 }
1160         }
1161
1162         /* we're done */
1163
1164         return 0;
1165 }                                  
1166
1167 int32_t
1168 Route::apply_some_plugin_counts (list<InsertCount>& iclist)
1169 {
1170         list<InsertCount>::iterator i;
1171
1172         for (i = iclist.begin(); i != iclist.end(); ++i) {
1173                 
1174                 if ((*i).insert->configure_io ((*i).cnt, (*i).in, (*i).out)) {
1175                         return -1;
1176                 }
1177                 /* make sure that however many we have, they are all active */
1178                 (*i).insert->activate ();
1179         }
1180
1181         return 0;
1182 }
1183
1184 int32_t
1185 Route::check_some_plugin_counts (list<InsertCount>& iclist, int32_t required_inputs, uint32_t* err_streams)
1186 {
1187         list<InsertCount>::iterator i;
1188         
1189         for (i = iclist.begin(); i != iclist.end(); ++i) {
1190
1191                 if (((*i).cnt = (*i).insert->can_support_input_configuration (required_inputs)) < 0) {
1192                         if (err_streams) {
1193                                 *err_streams = required_inputs;
1194                         }
1195                         return -1;
1196                 }
1197                 
1198                 (*i).in = required_inputs;
1199                 (*i).out = (*i).insert->compute_output_streams ((*i).cnt);
1200
1201                 required_inputs = (*i).out;
1202         }
1203
1204         return 0;
1205 }
1206
1207 int
1208 Route::copy_redirects (const Route& other, Placement placement, uint32_t* err_streams)
1209 {
1210         uint32_t old_rmo = redirect_max_outs;
1211
1212         if (err_streams) {
1213                 *err_streams = 0;
1214         }
1215
1216         RedirectList to_be_deleted;
1217
1218         {
1219                 Glib::RWLock::WriterLock lm (redirect_lock);
1220                 RedirectList::iterator tmp;
1221                 RedirectList the_copy;
1222
1223                 the_copy = _redirects;
1224                 
1225                 /* remove all relevant redirects */
1226
1227                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1228                         tmp = i;
1229                         ++tmp;
1230
1231                         if ((*i)->placement() == placement) {
1232                                 to_be_deleted.push_back (*i);
1233                                 _redirects.erase (i);
1234                         }
1235
1236                         i = tmp;
1237                 }
1238
1239                 /* now copy the relevant ones from "other" */
1240                 
1241                 for (RedirectList::const_iterator i = other._redirects.begin(); i != other._redirects.end(); ++i) {
1242                         if ((*i)->placement() == placement) {
1243                                 _redirects.push_back (Redirect::clone (*i));
1244                         }
1245                 }
1246
1247                 /* reset plugin stream handling */
1248
1249                 if (_reset_plugin_counts (err_streams)) {
1250
1251                         /* FAILED COPY ATTEMPT: we have to restore order */
1252
1253                         /* delete all cloned redirects */
1254
1255                         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1256
1257                                 tmp = i;
1258                                 ++tmp;
1259
1260                                 if ((*i)->placement() == placement) {
1261                                         _redirects.erase (i);
1262                                 }
1263                                 
1264                                 i = tmp;
1265                         }
1266
1267                         /* restore the natural order */
1268
1269                         _redirects = the_copy;
1270                         redirect_max_outs = old_rmo;
1271
1272                         /* we failed, even though things are OK again */
1273
1274                         return -1;
1275
1276                 } else {
1277                         
1278                         /* SUCCESSFUL COPY ATTEMPT: delete the redirects we removed pre-copy */
1279                         to_be_deleted.clear ();
1280                 }
1281         }
1282
1283         if (redirect_max_outs != old_rmo || old_rmo == 0) {
1284                 reset_panner ();
1285         }
1286
1287         redirects_changed (this); /* EMIT SIGNAL */
1288         return 0;
1289 }
1290
1291 void
1292 Route::all_redirects_flip ()
1293 {
1294         Glib::RWLock::ReaderLock lm (redirect_lock);
1295
1296         if (_redirects.empty()) {
1297                 return;
1298         }
1299
1300         bool first_is_on = _redirects.front()->active();
1301         
1302         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1303                 (*i)->set_active (!first_is_on, this);
1304         }
1305 }
1306
1307 void
1308 Route::all_redirects_active (bool state)
1309 {
1310         Glib::RWLock::ReaderLock lm (redirect_lock);
1311
1312         if (_redirects.empty()) {
1313                 return;
1314         }
1315
1316         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1317                 (*i)->set_active (state, this);
1318         }
1319 }
1320
1321 struct RedirectSorter {
1322     bool operator() (boost::shared_ptr<const Redirect> a, boost::shared_ptr<const Redirect> b) {
1323             return a->sort_key() < b->sort_key();
1324     }
1325 };
1326
1327 int
1328 Route::sort_redirects (uint32_t* err_streams)
1329 {
1330         {
1331                 RedirectSorter comparator;
1332                 Glib::RWLock::WriterLock lm (redirect_lock);
1333                 uint32_t old_rmo = redirect_max_outs;
1334
1335                 /* the sweet power of C++ ... */
1336
1337                 RedirectList as_it_was_before = _redirects;
1338
1339                 _redirects.sort (comparator);
1340         
1341                 if (_reset_plugin_counts (err_streams)) {
1342                         _redirects = as_it_was_before;
1343                         redirect_max_outs = old_rmo;
1344                         return -1;
1345                 } 
1346         } 
1347
1348         reset_panner ();
1349         redirects_changed (this); /* EMIT SIGNAL */
1350
1351         return 0;
1352 }
1353
1354 XMLNode&
1355 Route::get_state()
1356 {
1357         return state(true);
1358 }
1359
1360 XMLNode&
1361 Route::get_template()
1362 {
1363         return state(false);
1364 }
1365
1366 XMLNode&
1367 Route::state(bool full_state)
1368 {
1369         XMLNode *node = new XMLNode("Route");
1370         RedirectList:: iterator i;
1371         char buf[32];
1372
1373         if (_flags) {
1374                 node->add_property("flags", enum_2_string (_flags));
1375         }
1376         
1377         node->add_property("default-type", _default_type.to_string());
1378
1379         node->add_property("active", _active?"yes":"no");
1380         node->add_property("muted", _muted?"yes":"no");
1381         node->add_property("soloed", _soloed?"yes":"no");
1382         node->add_property("phase-invert", _phase_invert?"yes":"no");
1383         node->add_property("mute-affects-pre-fader", _mute_affects_pre_fader?"yes":"no"); 
1384         node->add_property("mute-affects-post-fader", _mute_affects_post_fader?"yes":"no"); 
1385         node->add_property("mute-affects-control-outs", _mute_affects_control_outs?"yes":"no"); 
1386         node->add_property("mute-affects-main-outs", _mute_affects_main_outs?"yes":"no"); 
1387
1388         if (_edit_group) {
1389                 node->add_property("edit-group", _edit_group->name());
1390         }
1391         if (_mix_group) {
1392                 node->add_property("mix-group", _mix_group->name());
1393         }
1394
1395         string order_string;
1396         OrderKeys::iterator x = order_keys.begin(); 
1397
1398         while (x != order_keys.end()) {
1399                 order_string += (*x).first;
1400                 order_string += '=';
1401                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1402                 order_string += buf;
1403                 
1404                 ++x;
1405
1406                 if (x == order_keys.end()) {
1407                         break;
1408                 }
1409
1410                 order_string += ':';
1411         }
1412         node->add_property ("order-keys", order_string);
1413
1414         node->add_child_nocopy (IO::state (full_state));
1415         node->add_child_nocopy (_solo_control.get_state ());
1416         node->add_child_nocopy (_mute_control.get_state ());
1417
1418         if (_control_outs) {
1419                 XMLNode* cnode = new XMLNode (X_("ControlOuts"));
1420                 cnode->add_child_nocopy (_control_outs->state (full_state));
1421                 node->add_child_nocopy (*cnode);
1422         }
1423
1424         if (_comment.length()) {
1425                 XMLNode *cmt = node->add_child ("Comment");
1426                 cmt->add_content (_comment);
1427         }
1428
1429         for (i = _redirects.begin(); i != _redirects.end(); ++i) {
1430                 node->add_child_nocopy((*i)->state (full_state));
1431         }
1432
1433         if (_extra_xml){
1434                 node->add_child_copy (*_extra_xml);
1435         }
1436         
1437         return *node;
1438 }
1439
1440 void
1441 Route::set_deferred_state ()
1442 {
1443         XMLNodeList nlist;
1444         XMLNodeConstIterator niter;
1445
1446         if (!deferred_state) {
1447                 return;
1448         }
1449
1450         nlist = deferred_state->children();
1451
1452         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1453                 add_redirect_from_xml (**niter);
1454         }
1455
1456         delete deferred_state;
1457         deferred_state = 0;
1458 }
1459
1460 void
1461 Route::add_redirect_from_xml (const XMLNode& node)
1462 {
1463         const XMLProperty *prop;
1464
1465         if (node.name() == "Send") {
1466                 
1467
1468                 try {
1469                         boost::shared_ptr<Send> send (new Send (_session, node));
1470                         add_redirect (send, this);
1471                 } 
1472                 
1473                 catch (failed_constructor &err) {
1474                         error << _("Send construction failed") << endmsg;
1475                         return;
1476                 }
1477                 
1478         } else if (node.name() == "Insert") {
1479                 
1480                 try {
1481                         if ((prop = node.property ("type")) != 0) {
1482
1483                                 boost::shared_ptr<Insert> insert;
1484
1485                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || prop->value() == "vst") {
1486
1487                                         insert.reset (new PluginInsert(_session, node));
1488                                         
1489                                 } else if (prop->value() == "port") {
1490
1491
1492                                         insert.reset (new PortInsert (_session, node));
1493
1494                                 } else {
1495
1496                                         error << string_compose(_("unknown Insert type \"%1\"; ignored"), prop->value()) << endmsg;
1497                                 }
1498
1499                                 add_redirect (insert, this);
1500                                 
1501                         } else {
1502                                 error << _("Insert XML node has no type property") << endmsg;
1503                         }
1504                 }
1505                 
1506                 catch (failed_constructor &err) {
1507                         warning << _("insert could not be created. Ignored.") << endmsg;
1508                         return;
1509                 }
1510         }
1511 }
1512
1513 int
1514 Route::set_state (const XMLNode& node)
1515 {
1516         return _set_state (node, true);
1517 }
1518
1519 int
1520 Route::_set_state (const XMLNode& node, bool call_base)
1521 {
1522         XMLNodeList nlist;
1523         XMLNodeConstIterator niter;
1524         XMLNode *child;
1525         XMLPropertyList plist;
1526         const XMLProperty *prop;
1527
1528         if (node.name() != "Route"){
1529                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1530                 return -1;
1531         }
1532
1533         if ((prop = node.property (X_("flags"))) != 0) {
1534                 _flags = Flag (string_2_enum (prop->value(), _flags));
1535         } else {
1536                 _flags = Flag (0);
1537         }
1538         
1539         if ((prop = node.property (X_("default-type"))) != 0) {
1540                 _default_type = DataType(prop->value());
1541                 assert(_default_type != DataType::NIL);
1542         }
1543
1544         if ((prop = node.property (X_("phase-invert"))) != 0) {
1545                 set_phase_invert(prop->value()=="yes"?true:false, this);
1546         }
1547
1548         if ((prop = node.property (X_("active"))) != 0) {
1549                 set_active (prop->value() == "yes");
1550         }
1551
1552         if ((prop = node.property (X_("muted"))) != 0) {
1553                 bool yn = prop->value()=="yes"?true:false; 
1554
1555                 /* force reset of mute status */
1556
1557                 _muted = !yn;
1558                 set_mute(yn, this);
1559                 mute_gain = desired_mute_gain;
1560         }
1561
1562         if ((prop = node.property (X_("soloed"))) != 0) {
1563                 bool yn = prop->value()=="yes"?true:false; 
1564
1565                 /* force reset of solo status */
1566
1567                 _soloed = !yn;
1568                 set_solo (yn, this);
1569                 solo_gain = desired_solo_gain;
1570         }
1571
1572         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
1573                 _mute_affects_pre_fader = (prop->value()=="yes")?true:false;
1574         }
1575
1576         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
1577                 _mute_affects_post_fader = (prop->value()=="yes")?true:false;
1578         }
1579
1580         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
1581                 _mute_affects_control_outs = (prop->value()=="yes")?true:false;
1582         }
1583
1584         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
1585                 _mute_affects_main_outs = (prop->value()=="yes")?true:false;
1586         }
1587
1588         if ((prop = node.property (X_("edit-group"))) != 0) {
1589                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
1590                 if(edit_group == 0) {
1591                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1592                 } else {
1593                         set_edit_group(edit_group, this);
1594                 }
1595         }
1596
1597         if ((prop = node.property (X_("order-keys"))) != 0) {
1598
1599                 long n;
1600
1601                 string::size_type colon, equal;
1602                 string remaining = prop->value();
1603
1604                 while (remaining.length()) {
1605
1606                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1607                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1608                                       << endmsg;
1609                         } else {
1610                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1611                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1612                                               << endmsg;
1613                                 } else {
1614                                         set_order_key (remaining.substr (0, equal), n);
1615                                 }
1616                         }
1617
1618                         colon = remaining.find_first_of (':');
1619
1620                         if (colon != string::npos) {
1621                                 remaining = remaining.substr (colon+1);
1622                         } else {
1623                                 break;
1624                         }
1625                 }
1626         }
1627
1628         nlist = node.children();
1629
1630         if (deferred_state) {
1631                 delete deferred_state;
1632         }
1633
1634         deferred_state = new XMLNode(X_("deferred state"));
1635
1636         /* set parent class properties before anything else */
1637
1638         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1639
1640                 child = *niter;
1641
1642                 if (child->name() == IO::state_node_name && call_base) {
1643
1644                         IO::set_state (*child);
1645                         break;
1646                 }
1647         }
1648                         
1649         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1650
1651                 child = *niter;
1652                         
1653                 if (child->name() == X_("Send")) {
1654
1655
1656                         if (!IO::ports_legal) {
1657
1658                                 deferred_state->add_child_copy (*child);
1659
1660                         } else {
1661                                 add_redirect_from_xml (*child);
1662                         }
1663
1664                 } else if (child->name() == X_("Insert")) {
1665                         
1666                         if (!IO::ports_legal) {
1667                                 
1668                                 deferred_state->add_child_copy (*child);
1669
1670                         } else {
1671                                 
1672                                 add_redirect_from_xml (*child);
1673                         }
1674
1675                 } else if (child->name() == X_("Automation")) {
1676                         
1677                         if ((prop = child->property (X_("path"))) != 0)  {
1678                                 load_automation (prop->value());
1679                         }
1680
1681                 } else if (child->name() == X_("ControlOuts")) {
1682                         
1683                         string coutname = _name;
1684                         coutname += _("[control]");
1685
1686                         _control_outs = new IO (_session, coutname);
1687                         _control_outs->set_state (**(child->children().begin()));
1688
1689                 } else if (child->name() == X_("Comment")) {
1690
1691                         /* XXX this is a terrible API design in libxml++ */
1692
1693                         XMLNode *cmt = *(child->children().begin());
1694                         _comment = cmt->content();
1695
1696                 } else if (child->name() == X_("extra")) {
1697
1698                         _extra_xml = new XMLNode (*child);
1699
1700                 } else if (child->name() == X_("controllable") && (prop = child->property("name")) != 0) {
1701                         
1702                         if (prop->value() == "solo") {
1703                                 _solo_control.set_state (*child);
1704                                 _session.add_controllable (&_solo_control);
1705                         }
1706                         else if (prop->value() == "mute") {
1707                                 _mute_control.set_state (*child);
1708                                 _session.add_controllable (&_mute_control);
1709                         }
1710                 }
1711         }
1712
1713         if ((prop = node.property (X_("mix-group"))) != 0) {
1714                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
1715                 if (mix_group == 0) {
1716                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1717                 }  else {
1718                         set_mix_group(mix_group, this);
1719                 }
1720         }
1721
1722         return 0;
1723 }
1724
1725 void
1726 Route::curve_reallocate ()
1727 {
1728 //      _gain_automation_curve.finish_resize ();
1729 //      _pan_automation_curve.finish_resize ();
1730 }
1731
1732 void
1733 Route::silence (nframes_t nframes, nframes_t offset)
1734 {
1735         if (!_silent) {
1736
1737                 // reset_peak_meters ();
1738                 
1739                 IO::silence (nframes, offset);
1740
1741                 if (_control_outs) {
1742                         _control_outs->silence (nframes, offset);
1743                 }
1744
1745                 { 
1746                         Glib::RWLock::ReaderLock lm (redirect_lock, Glib::TRY_LOCK);
1747                         
1748                         if (lm.locked()) {
1749                                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1750                                         boost::shared_ptr<PluginInsert> pi;
1751                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
1752                                                 // skip plugins, they don't need anything when we're not active
1753                                                 continue;
1754                                         }
1755
1756                                         (*i)->silence (nframes, offset);
1757                                 }
1758
1759                                 if (nframes == _session.get_block_size() && offset == 0) {
1760                                         // _silent = true;
1761                                 }
1762                         }
1763                 }
1764                 
1765         }
1766 }       
1767
1768 int
1769 Route::set_control_outs (const vector<string>& ports)
1770 {
1771         Glib::Mutex::Lock lm (control_outs_lock);
1772         vector<string>::const_iterator i;
1773
1774         if (_control_outs) {
1775                 delete _control_outs;
1776                 _control_outs = 0;
1777         }
1778         
1779         if (ports.empty()) {
1780                 return 0;
1781         }
1782  
1783         string coutname = _name;
1784         coutname += _("[control]");
1785         
1786         _control_outs = new IO (_session, coutname);
1787
1788         /* our control outs need as many outputs as we
1789            have outputs. we track the changes in ::output_change_handler().
1790         */
1791
1792         _control_outs->ensure_io (0, n_outputs(), true, this);
1793  
1794         return 0;
1795 }       
1796
1797 void
1798 Route::set_edit_group (RouteGroup *eg, void *src)
1799
1800 {
1801         if (eg == _edit_group) {
1802                 return;
1803         }
1804
1805         if (_edit_group) {
1806                 _edit_group->remove (this);
1807         }
1808
1809         if ((_edit_group = eg) != 0) {
1810                 _edit_group->add (this);
1811         }
1812
1813         _session.set_dirty ();
1814         edit_group_changed (src); /* EMIT SIGNAL */
1815 }
1816
1817 void
1818 Route::drop_edit_group (void *src)
1819 {
1820         _edit_group = 0;
1821         _session.set_dirty ();
1822         edit_group_changed (src); /* EMIT SIGNAL */
1823 }
1824
1825 void
1826 Route::set_mix_group (RouteGroup *mg, void *src)
1827
1828 {
1829         if (mg == _mix_group) {
1830                 return;
1831         }
1832
1833         if (_mix_group) {
1834                 _mix_group->remove (this);
1835         }
1836
1837         if ((_mix_group = mg) != 0) {
1838                 _mix_group->add (this);
1839         }
1840
1841         _session.set_dirty ();
1842         mix_group_changed (src); /* EMIT SIGNAL */
1843 }
1844
1845 void
1846 Route::drop_mix_group (void *src)
1847 {
1848         _mix_group = 0;
1849         _session.set_dirty ();
1850         mix_group_changed (src); /* EMIT SIGNAL */
1851 }
1852
1853 void
1854 Route::set_comment (string cmt, void *src)
1855 {
1856         _comment = cmt;
1857         comment_changed (src);
1858         _session.set_dirty ();
1859 }
1860
1861 bool
1862 Route::feeds (boost::shared_ptr<Route> other)
1863 {
1864         uint32_t i, j;
1865
1866         IO& self = *this;
1867         uint32_t no = self.n_outputs();
1868         uint32_t ni = other->n_inputs ();
1869
1870         for (i = 0; i < no; ++i) {
1871                 for (j = 0; j < ni; ++j) {
1872                         if (self.output(i)->connected_to (other->input(j)->name())) {
1873                                 return true;
1874                         }
1875                 }
1876         }
1877
1878         /* check Redirects which may also interconnect Routes */
1879
1880         for (RedirectList::iterator r = _redirects.begin(); r != _redirects.end(); r++) {
1881
1882                 no = (*r)->n_outputs();
1883
1884                 for (i = 0; i < no; ++i) {
1885                         for (j = 0; j < ni; ++j) {
1886                                 if ((*r)->output(i)->connected_to (other->input (j)->name())) {
1887                                         return true;
1888                                 }
1889                         }
1890                 }
1891         }
1892
1893         /* check for control room outputs which may also interconnect Routes */
1894
1895         if (_control_outs) {
1896
1897                 no = _control_outs->n_outputs();
1898                 
1899                 for (i = 0; i < no; ++i) {
1900                         for (j = 0; j < ni; ++j) {
1901                                 if (_control_outs->output(i)->connected_to (other->input (j)->name())) {
1902                                         return true;
1903                                 }
1904                         }
1905                 }
1906         }
1907
1908         return false;
1909 }
1910
1911 void
1912 Route::set_mute_config (mute_type t, bool onoff, void *src)
1913 {
1914         switch (t) {
1915         case PRE_FADER:
1916                 _mute_affects_pre_fader = onoff;
1917                  pre_fader_changed(src); /* EMIT SIGNAL */
1918                 break;
1919
1920         case POST_FADER:
1921                 _mute_affects_post_fader = onoff;
1922                  post_fader_changed(src); /* EMIT SIGNAL */
1923                 break;
1924
1925         case CONTROL_OUTS:
1926                 _mute_affects_control_outs = onoff;
1927                  control_outs_changed(src); /* EMIT SIGNAL */
1928                 break;
1929
1930         case MAIN_OUTS:
1931                 _mute_affects_main_outs = onoff;
1932                  main_outs_changed(src); /* EMIT SIGNAL */
1933                 break;
1934         }
1935 }
1936
1937 bool
1938 Route::get_mute_config (mute_type t)
1939 {
1940         bool onoff = false;
1941         
1942         switch (t){
1943         case PRE_FADER:
1944                 onoff = _mute_affects_pre_fader; 
1945                 break;
1946         case POST_FADER:
1947                 onoff = _mute_affects_post_fader;
1948                 break;
1949         case CONTROL_OUTS:
1950                 onoff = _mute_affects_control_outs;
1951                 break;
1952         case MAIN_OUTS:
1953                 onoff = _mute_affects_main_outs;
1954                 break;
1955         }
1956         
1957         return onoff;
1958 }
1959
1960 void
1961 Route::set_active (bool yn)
1962 {
1963         _active = yn; 
1964          active_changed(); /* EMIT SIGNAL */
1965 }
1966
1967 void
1968 Route::handle_transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_redirects)
1969 {
1970         nframes_t now = _session.transport_frame();
1971
1972         {
1973                 Glib::RWLock::ReaderLock lm (redirect_lock);
1974
1975                 if (!did_locate) {
1976                         automation_snapshot (now);
1977                 }
1978
1979                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1980                         
1981                         if (Config->get_plugins_stop_with_transport() && can_flush_redirects) {
1982                                 (*i)->deactivate ();
1983                                 (*i)->activate ();
1984                         }
1985                         
1986                         (*i)->transport_stopped (now);
1987                 }
1988         }
1989
1990         IO::transport_stopped (now);
1991  
1992         _roll_delay = _initial_delay;
1993 }
1994
1995 void
1996 Route::input_change_handler (IOChange change, void *ignored)
1997 {
1998         if (change & ConfigurationChanged) {
1999                 reset_plugin_counts (0);
2000         }
2001 }
2002
2003 void
2004 Route::output_change_handler (IOChange change, void *ignored)
2005 {
2006         if (change & ConfigurationChanged) {
2007                 if (_control_outs) {
2008                         _control_outs->ensure_io (0, n_outputs(), true, this);
2009                 }
2010                 
2011                 reset_plugin_counts (0);
2012         }
2013 }
2014
2015 uint32_t
2016 Route::pans_required () const
2017 {
2018         if (n_outputs() < 2) {
2019                 return 0;
2020         }
2021         
2022         return max (n_inputs (), redirect_max_outs);
2023 }
2024
2025 int 
2026 Route::no_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
2027                    bool session_state_changing, bool can_record, bool rec_monitors_input)
2028 {
2029         if (n_outputs() == 0) {
2030                 return 0;
2031         }
2032
2033         if (session_state_changing || !_active)  {
2034                 silence (nframes, offset);
2035                 return 0;
2036         }
2037
2038         apply_gain_automation = false;
2039         
2040         if (n_inputs()) {
2041                 passthru (start_frame, end_frame, nframes, offset, 0, false);
2042         } else {
2043                 silence (nframes, offset);
2044         }
2045
2046         return 0;
2047 }
2048
2049 nframes_t
2050 Route::check_initial_delay (nframes_t nframes, nframes_t& offset, nframes_t& transport_frame)
2051 {
2052         if (_roll_delay > nframes) {
2053
2054                 _roll_delay -= nframes;
2055                 silence (nframes, offset);
2056                 /* transport frame is not legal for caller to use */
2057                 return 0;
2058
2059         } else if (_roll_delay > 0) {
2060
2061                 nframes -= _roll_delay;
2062
2063                 silence (_roll_delay, offset);
2064
2065                 offset += _roll_delay;
2066                 transport_frame += _roll_delay;
2067
2068                 _roll_delay = 0;
2069         }
2070
2071         return nframes;
2072 }
2073
2074 int
2075 Route::roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, int declick,
2076              bool can_record, bool rec_monitors_input)
2077 {
2078         {
2079                 Glib::RWLock::ReaderLock lm (redirect_lock, Glib::TRY_LOCK);
2080                 if (lm.locked()) {
2081                         // automation snapshot can also be called from the non-rt context
2082                         // and it uses the redirect list, so we take the lock out here
2083                         automation_snapshot (_session.transport_frame());
2084                 }
2085         }
2086
2087         if ((n_outputs() == 0 && _redirects.empty()) || n_inputs() == 0 || !_active) {
2088                 silence (nframes, offset);
2089                 return 0;
2090         }
2091         
2092         nframes_t unused = 0;
2093
2094         if ((nframes = check_initial_delay (nframes, offset, unused)) == 0) {
2095                 return 0;
2096         }
2097
2098         _silent = false;
2099
2100         apply_gain_automation = false;
2101
2102         { 
2103                 Glib::Mutex::Lock am (automation_lock, Glib::TRY_LOCK);
2104                 
2105                 if (am.locked() && _session.transport_rolling()) {
2106                         
2107                         nframes_t start_frame = end_frame - nframes;
2108                         
2109                         if (gain_automation_playback()) {
2110                                 apply_gain_automation = _gain_automation_curve.rt_safe_get_vector (start_frame, end_frame, _session.gain_automation_buffer(), nframes);
2111                         }
2112                 }
2113         }
2114
2115         passthru (start_frame, end_frame, nframes, offset, declick, false);
2116
2117         return 0;
2118 }
2119
2120 int
2121 Route::silent_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
2122                     bool can_record, bool rec_monitors_input)
2123 {
2124         silence (nframes, offset);
2125         return 0;
2126 }
2127
2128 void
2129 Route::toggle_monitor_input ()
2130 {
2131         for (vector<Port*>::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2132                 (*i)->ensure_monitor_input(!(*i)->monitoring_input());
2133         }
2134 }
2135
2136 bool
2137 Route::has_external_redirects () const
2138 {
2139         boost::shared_ptr<const PortInsert> pi;
2140         
2141         for (RedirectList::const_iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2142                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2143
2144                         uint32_t no = pi->n_outputs();
2145
2146                         for (uint32_t n = 0; n < no; ++n) {
2147                                 
2148                                 string port_name = pi->output(n)->name();
2149                                 string client_name = port_name.substr (0, port_name.find(':'));
2150
2151                                 /* only say "yes" if the redirect is actually in use */
2152                                 
2153                                 if (client_name != "ardour" && pi->active()) {
2154                                         return true;
2155                                 }
2156                         }
2157                 }
2158         }
2159
2160         return false;
2161 }
2162
2163 void
2164 Route::flush_redirects ()
2165 {
2166         /* XXX shouldn't really try to take this lock, since
2167            this is called from the RT audio thread.
2168         */
2169
2170         Glib::RWLock::ReaderLock lm (redirect_lock);
2171
2172         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2173                 (*i)->deactivate ();
2174                 (*i)->activate ();
2175         }
2176 }
2177
2178 void
2179 Route::set_meter_point (MeterPoint p, void *src)
2180 {
2181         if (_meter_point != p) {
2182                 _meter_point = p;
2183                  meter_change (src); /* EMIT SIGNAL */
2184                 _session.set_dirty ();
2185         }
2186 }
2187
2188 nframes_t
2189 Route::update_total_latency ()
2190 {
2191         _own_latency = 0;
2192
2193         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2194                 if ((*i)->active ()) {
2195                         _own_latency += (*i)->latency ();
2196                 }
2197         }
2198
2199         set_port_latency (_own_latency);
2200
2201         /* this (virtual) function is used for pure Routes,
2202            not derived classes like AudioTrack.  this means
2203            that the data processed here comes from an input
2204            port, not prerecorded material, and therefore we
2205            have to take into account any input latency.
2206         */
2207
2208         _own_latency += input_latency ();
2209
2210         return _own_latency;
2211 }
2212
2213 void
2214 Route::set_latency_delay (nframes_t longest_session_latency)
2215 {
2216         _initial_delay = longest_session_latency - _own_latency;
2217
2218         if (_session.transport_stopped()) {
2219                 _roll_delay = _initial_delay;
2220         }
2221 }
2222
2223 void
2224 Route::automation_snapshot (nframes_t now)
2225 {
2226         IO::automation_snapshot (now);
2227
2228         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2229                 (*i)->automation_snapshot (now);
2230         }
2231 }
2232
2233 Route::ToggleControllable::ToggleControllable (std::string name, Route& s, ToggleType tp)
2234         : Controllable (name), route (s), type(tp)
2235 {
2236         
2237 }
2238
2239 void
2240 Route::ToggleControllable::set_value (float val)
2241 {
2242         bool bval = ((val >= 0.5f) ? true: false);
2243         
2244         switch (type) {
2245         case MuteControl:
2246                 route.set_mute (bval, this);
2247                 break;
2248         case SoloControl:
2249                 route.set_solo (bval, this);
2250                 break;
2251         default:
2252                 break;
2253         }
2254 }
2255
2256 float
2257 Route::ToggleControllable::get_value (void) const
2258 {
2259         float val = 0.0f;
2260         
2261         switch (type) {
2262         case MuteControl:
2263                 val = route.muted() ? 1.0f : 0.0f;
2264                 break;
2265         case SoloControl:
2266                 val = route.soloed() ? 1.0f : 0.0f;
2267                 break;
2268         default:
2269                 break;
2270         }
2271
2272         return val;
2273 }
2274
2275 void 
2276 Route::set_block_size (nframes_t nframes)
2277 {
2278         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2279                 (*i)->set_block_size (nframes);
2280         }
2281 }
2282
2283 void
2284 Route::redirect_active_proxy (Redirect* ignored, void* ignored_src)
2285 {
2286         _session.update_latency_compensation (false, false);
2287 }
2288
2289 void
2290 Route::protect_automation ()
2291 {
2292         switch (gain_automation_state()) {
2293         case Write:
2294         case Touch:
2295                 set_gain_automation_state (Off);
2296                 break;
2297         default:
2298                 break;
2299         }
2300
2301         switch (panner().automation_state ()) {
2302         case Write:
2303         case Touch:
2304                 panner().set_automation_state (Off);
2305                 break;
2306         default:
2307                 break;
2308         }
2309         
2310         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2311                 boost::shared_ptr<PluginInsert> pi;
2312                 if ((pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2313                         pi->protect_automation ();
2314                 }
2315         }
2316 }
2317
2318 void
2319 Route::set_pending_declick (int declick)
2320 {
2321         if (_declickable) {
2322                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2323                 if (declick) {
2324                         _pending_declick = declick;
2325                 }
2326                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2327         } else {
2328                 _pending_declick = 0;
2329         }
2330
2331 }