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