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