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