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