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