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