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