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