- Fixed port adding/removing/connecting and related bugs with route signal path
[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                 ChanCount potential_max_streams;
763
764                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(redirect)) != 0) {
765                         pi->set_count (1);
766
767                         if (pi->input_streams() == ChanCount::ZERO) {
768                                 /* generator plugin */
769                                 _have_internal_generator = true;
770                         }
771
772                         potential_max_streams = max(pi->input_streams(), pi->output_streams());
773                         
774                 } else if ((porti = boost::dynamic_pointer_cast<PortInsert>(redirect)) != 0) {
775
776                         /* force new port inserts to start out with an i/o configuration
777                            that matches this route's i/o configuration.
778
779                            the "inputs" for the port are supposed to match the output
780                            of this route.
781
782                            the "outputs" of the route should match the inputs of this
783                            route. XXX shouldn't they match the number of active signal
784                            streams at the point of insertion?
785                            
786                         */
787
788                         porti->ensure_io (n_outputs (), n_inputs(), false, this);
789                 }
790
791                 // Ensure peak vector sizes before the plugin is activated
792                 _meter->setup(potential_max_streams);
793
794                 _redirects.push_back (redirect);
795
796                 if (_reset_plugin_counts (err_streams)) {
797                         _redirects.pop_back ();
798                         _reset_plugin_counts (0); // it worked before we tried to add it ...
799                         return -1;
800                 }
801
802                 redirect->activate ();
803                 redirect->active_changed.connect (mem_fun (*this, &Route::redirect_active_proxy));
804         }
805         
806         if (redirect_max_outs != old_rmo || old_rmo == ChanCount::ZERO) {
807                 reset_panner ();
808         }
809
810
811         redirects_changed (src); /* EMIT SIGNAL */
812         return 0;
813 }
814
815 int
816 Route::add_redirects (const RedirectList& others, void *src, uint32_t* err_streams)
817 {
818         ChanCount old_rmo = redirect_max_outs;
819
820         if (!_session.engine().connected()) {
821                 return 1;
822         }
823
824         {
825                 Glib::RWLock::WriterLock lm (redirect_lock);
826
827                 RedirectList::iterator existing_end = _redirects.end();
828                 --existing_end;
829
830                 ChanCount potential_max_streams;
831
832                 for (RedirectList::const_iterator i = others.begin(); i != others.end(); ++i) {
833                         
834                         boost::shared_ptr<PluginInsert> pi;
835                         
836                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
837                                 pi->set_count (1);
838                                 
839                                 ChanCount m = max(pi->input_streams(), pi->output_streams());
840                                 if (m > potential_max_streams)
841                                         potential_max_streams = m;
842                         }
843
844                         // Ensure peak vector sizes before the plugin is activated
845                         _meter->setup(potential_max_streams);
846
847                         _redirects.push_back (*i);
848                         
849                         if (_reset_plugin_counts (err_streams)) {
850                                 ++existing_end;
851                                 _redirects.erase (existing_end, _redirects.end());
852                                 _reset_plugin_counts (0); // it worked before we tried to add it ...
853                                 return -1;
854                         }
855                         
856                         (*i)->activate ();
857                         (*i)->active_changed.connect (mem_fun (*this, &Route::redirect_active_proxy));
858                 }
859         }
860         
861         if (redirect_max_outs != old_rmo || old_rmo == ChanCount::ZERO) {
862                 reset_panner ();
863         }
864
865         redirects_changed (src); /* EMIT SIGNAL */
866         return 0;
867 }
868
869 void
870 Route::clear_redirects (void *src)
871 {
872         ChanCount old_rmo = redirect_max_outs;
873
874         if (!_session.engine().connected()) {
875                 return;
876         }
877
878         {
879                 Glib::RWLock::WriterLock lm (redirect_lock);
880                 _redirects.clear ();
881         }
882
883         if (redirect_max_outs != old_rmo) {
884                 reset_panner ();
885         }
886         
887         redirect_max_outs.reset();
888         _have_internal_generator = false;
889         redirects_changed (src); /* EMIT SIGNAL */
890 }
891
892 int
893 Route::remove_redirect (boost::shared_ptr<Redirect> redirect, void *src, uint32_t* err_streams)
894 {
895         ChanCount old_rmo = redirect_max_outs;
896
897         if (!_session.engine().connected()) {
898                 return 1;
899         }
900
901         redirect_max_outs.reset();
902
903         {
904                 Glib::RWLock::WriterLock lm (redirect_lock);
905                 RedirectList::iterator i;
906                 bool removed = false;
907
908                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
909                         if (*i == redirect) {
910
911                                 RedirectList::iterator tmp;
912
913                                 /* move along, see failure case for reset_plugin_counts()
914                                    where we may need to reinsert the redirect.
915                                 */
916
917                                 tmp = i;
918                                 ++tmp;
919
920                                 /* stop redirects that send signals to JACK ports
921                                    from causing noise as a result of no longer being
922                                    run.
923                                 */
924
925                                 boost::shared_ptr<Send> send;
926                                 boost::shared_ptr<PortInsert> port_insert;
927                                 
928                                 if ((send = boost::dynamic_pointer_cast<Send> (*i)) != 0) {
929                                         send->disconnect_inputs (this);
930                                         send->disconnect_outputs (this);
931                                 } else if ((port_insert = boost::dynamic_pointer_cast<PortInsert> (*i)) != 0) {
932                                         port_insert->disconnect_inputs (this);
933                                         port_insert->disconnect_outputs (this);
934                                 }
935
936                                 _redirects.erase (i);
937
938                                 i = tmp;
939                                 removed = true;
940                                 break;
941                         }
942                 }
943
944                 if (!removed) {
945                         /* what? */
946                         return 1;
947                 }
948
949                 if (_reset_plugin_counts (err_streams)) {
950                         /* get back to where we where */
951                         _redirects.insert (i, redirect);
952                         /* we know this will work, because it worked before :) */
953                         _reset_plugin_counts (0);
954                         return -1;
955                 }
956
957                 bool foo = false;
958
959                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
960                         boost::shared_ptr<PluginInsert> pi;
961                         
962                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
963                                 if (pi->is_generator()) {
964                                         foo = true;
965                                 }
966                         }
967                 }
968
969                 _have_internal_generator = foo;
970         }
971
972         if (old_rmo != redirect_max_outs) {
973                 reset_panner ();
974         }
975
976         redirects_changed (src); /* EMIT SIGNAL */
977         return 0;
978 }
979
980 int
981 Route::reset_plugin_counts (uint32_t* lpc)
982 {
983         Glib::RWLock::WriterLock lm (redirect_lock);
984         return _reset_plugin_counts (lpc);
985 }
986
987
988 int
989 Route::_reset_plugin_counts (uint32_t* err_streams)
990 {
991         RedirectList::iterator r;
992         uint32_t i_cnt;
993         uint32_t s_cnt;
994         map<Placement,list<InsertCount> > insert_map;
995         jack_nframes_t initial_streams;
996
997         redirect_max_outs.reset();
998         i_cnt = 0;
999         s_cnt = 0;
1000
1001         /* divide inserts up by placement so we get the signal flow
1002            properly modelled. we need to do this because the _redirects
1003            list is not sorted by placement, and because other reasons may 
1004            exist now or in the future for this separate treatment.
1005         */
1006         
1007         for (r = _redirects.begin(); r != _redirects.end(); ++r) {
1008
1009                 boost::shared_ptr<Insert> insert;
1010
1011                 /* do this here in case we bomb out before we get to the end of
1012                    this function.
1013                 */
1014
1015                 redirect_max_outs = max ((*r)->output_streams (), redirect_max_outs);
1016
1017                 if ((insert = boost::dynamic_pointer_cast<Insert>(*r)) != 0) {
1018                         ++i_cnt;
1019                         insert_map[insert->placement()].push_back (InsertCount (insert));
1020
1021                         /* reset plugin counts back to one for now so
1022                            that we have a predictable, controlled
1023                            state to try to configure.
1024                         */
1025
1026                         boost::shared_ptr<PluginInsert> pi;
1027                 
1028                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(insert)) != 0) {
1029                                 pi->set_count (1);
1030                         }
1031
1032                 } else if (boost::dynamic_pointer_cast<Send> (*r) != 0) {
1033                         ++s_cnt;
1034                 }
1035         }
1036         
1037         if (i_cnt == 0) {
1038                 if (s_cnt) {
1039                         goto recompute;
1040                 } else {
1041                         return 0;
1042                 }
1043         }
1044
1045         /* Now process each placement in order, checking to see if we 
1046            can really do what has been requested.
1047         */
1048
1049         /* A: PreFader */
1050         
1051         if (check_some_plugin_counts (insert_map[PreFader], n_inputs ().get(_default_type), err_streams)) {
1052                 return -1;
1053         }
1054
1055         /* figure out the streams that will feed into PreFader */
1056
1057         if (!insert_map[PreFader].empty()) {
1058                 InsertCount& ic (insert_map[PreFader].back());
1059                 initial_streams = ic.insert->compute_output_streams (ic.cnt);
1060         } else {
1061                 initial_streams = n_inputs ().get(_default_type);
1062         }
1063
1064         /* B: PostFader */
1065
1066         if (check_some_plugin_counts (insert_map[PostFader], initial_streams, err_streams)) {
1067                 return -1;
1068         }
1069
1070         /* OK, everything can be set up correctly, so lets do it */
1071
1072         apply_some_plugin_counts (insert_map[PreFader]);
1073         apply_some_plugin_counts (insert_map[PostFader]);
1074
1075         /* recompute max outs of any redirect */
1076
1077   recompute:
1078
1079         redirect_max_outs.reset();
1080         RedirectList::iterator prev = _redirects.end();
1081
1082         for (r = _redirects.begin(); r != _redirects.end(); prev = r, ++r) {
1083                 boost::shared_ptr<Send> s;
1084
1085                 if ((s = boost::dynamic_pointer_cast<Send> (*r)) != 0) {
1086                         if (r == _redirects.begin()) {
1087                                 s->expect_inputs (n_inputs());
1088                         } else {
1089                                 s->expect_inputs ((*prev)->output_streams());
1090                         }
1091                 }
1092
1093                 redirect_max_outs = max ((*r)->output_streams(), redirect_max_outs);
1094         }
1095
1096         /* we're done */
1097
1098         return 0;
1099 }                                  
1100
1101 int32_t
1102 Route::apply_some_plugin_counts (list<InsertCount>& iclist)
1103 {
1104         list<InsertCount>::iterator i;
1105
1106         for (i = iclist.begin(); i != iclist.end(); ++i) {
1107                 
1108                 if ((*i).insert->configure_io ((*i).cnt, (*i).in, (*i).out)) {
1109                         return -1;
1110                 }
1111                 /* make sure that however many we have, they are all active */
1112                 (*i).insert->activate ();
1113         }
1114
1115         return 0;
1116 }
1117
1118 int32_t
1119 Route::check_some_plugin_counts (list<InsertCount>& iclist, int32_t required_inputs, uint32_t* err_streams)
1120 {
1121         list<InsertCount>::iterator i;
1122         
1123         for (i = iclist.begin(); i != iclist.end(); ++i) {
1124
1125                 if (((*i).cnt = (*i).insert->can_support_input_configuration (required_inputs)) < 0) {
1126                         if (err_streams) {
1127                                 *err_streams = required_inputs;
1128                         }
1129                         return -1;
1130                 }
1131                 
1132                 (*i).in = required_inputs;
1133                 (*i).out = (*i).insert->compute_output_streams ((*i).cnt);
1134
1135                 required_inputs = (*i).out;
1136         }
1137
1138         return 0;
1139 }
1140
1141 int
1142 Route::copy_redirects (const Route& other, Placement placement, uint32_t* err_streams)
1143 {
1144         ChanCount old_rmo = redirect_max_outs;
1145
1146         if (err_streams) {
1147                 *err_streams = 0;
1148         }
1149
1150         RedirectList to_be_deleted;
1151
1152         {
1153                 Glib::RWLock::WriterLock lm (redirect_lock);
1154                 RedirectList::iterator tmp;
1155                 RedirectList the_copy;
1156
1157                 the_copy = _redirects;
1158                 
1159                 /* remove all relevant redirects */
1160
1161                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1162                         tmp = i;
1163                         ++tmp;
1164
1165                         if ((*i)->placement() == placement) {
1166                                 to_be_deleted.push_back (*i);
1167                                 _redirects.erase (i);
1168                         }
1169
1170                         i = tmp;
1171                 }
1172
1173                 /* now copy the relevant ones from "other" */
1174                 
1175                 for (RedirectList::const_iterator i = other._redirects.begin(); i != other._redirects.end(); ++i) {
1176                         if ((*i)->placement() == placement) {
1177                                 _redirects.push_back (Redirect::clone (*i));
1178                         }
1179                 }
1180
1181                 /* reset plugin stream handling */
1182
1183                 if (_reset_plugin_counts (err_streams)) {
1184
1185                         /* FAILED COPY ATTEMPT: we have to restore order */
1186
1187                         /* delete all cloned redirects */
1188
1189                         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1190
1191                                 tmp = i;
1192                                 ++tmp;
1193
1194                                 if ((*i)->placement() == placement) {
1195                                         _redirects.erase (i);
1196                                 }
1197                                 
1198                                 i = tmp;
1199                         }
1200
1201                         /* restore the natural order */
1202
1203                         _redirects = the_copy;
1204                         redirect_max_outs = old_rmo;
1205
1206                         /* we failed, even though things are OK again */
1207
1208                         return -1;
1209
1210                 } else {
1211                         
1212                         /* SUCCESSFUL COPY ATTEMPT: delete the redirects we removed pre-copy */
1213                         to_be_deleted.clear ();
1214                 }
1215         }
1216
1217         if (redirect_max_outs != old_rmo || old_rmo == ChanCount::ZERO) {
1218                 reset_panner ();
1219         }
1220
1221         redirects_changed (this); /* EMIT SIGNAL */
1222         return 0;
1223 }
1224
1225 void
1226 Route::all_redirects_flip ()
1227 {
1228         Glib::RWLock::ReaderLock lm (redirect_lock);
1229
1230         if (_redirects.empty()) {
1231                 return;
1232         }
1233
1234         bool first_is_on = _redirects.front()->active();
1235         
1236         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1237                 (*i)->set_active (!first_is_on, this);
1238         }
1239 }
1240
1241 void
1242 Route::all_redirects_active (bool state)
1243 {
1244         Glib::RWLock::ReaderLock lm (redirect_lock);
1245
1246         if (_redirects.empty()) {
1247                 return;
1248         }
1249
1250         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1251                 (*i)->set_active (state, this);
1252         }
1253 }
1254
1255 struct RedirectSorter {
1256     bool operator() (boost::shared_ptr<const Redirect> a, boost::shared_ptr<const Redirect> b) {
1257             return a->sort_key() < b->sort_key();
1258     }
1259 };
1260
1261 int
1262 Route::sort_redirects (uint32_t* err_streams)
1263 {
1264         {
1265                 RedirectSorter comparator;
1266                 Glib::RWLock::WriterLock lm (redirect_lock);
1267                 ChanCount old_rmo = redirect_max_outs;
1268
1269                 /* the sweet power of C++ ... */
1270
1271                 RedirectList as_it_was_before = _redirects;
1272
1273                 _redirects.sort (comparator);
1274         
1275                 if (_reset_plugin_counts (err_streams)) {
1276                         _redirects = as_it_was_before;
1277                         redirect_max_outs = old_rmo;
1278                         return -1;
1279                 } 
1280         } 
1281
1282         reset_panner ();
1283         redirects_changed (this); /* EMIT SIGNAL */
1284
1285         return 0;
1286 }
1287
1288 XMLNode&
1289 Route::get_state()
1290 {
1291         return state(true);
1292 }
1293
1294 XMLNode&
1295 Route::get_template()
1296 {
1297         return state(false);
1298 }
1299
1300 XMLNode&
1301 Route::state(bool full_state)
1302 {
1303         XMLNode *node = new XMLNode("Route");
1304         XMLNode *aevents;
1305         RedirectList:: iterator i;
1306         char buf[32];
1307
1308         if (_flags) {
1309                 snprintf (buf, sizeof (buf), "0x%x", _flags);
1310                 node->add_property("flags", buf);
1311         }
1312         
1313         node->add_property("default-type", _default_type.to_string());
1314
1315         node->add_property("active", _active?"yes":"no");
1316         node->add_property("muted", _muted?"yes":"no");
1317         node->add_property("soloed", _soloed?"yes":"no");
1318         node->add_property("phase-invert", _phase_invert?"yes":"no");
1319         node->add_property("mute-affects-pre-fader", _mute_affects_pre_fader?"yes":"no"); 
1320         node->add_property("mute-affects-post-fader", _mute_affects_post_fader?"yes":"no"); 
1321         node->add_property("mute-affects-control-outs", _mute_affects_control_outs?"yes":"no"); 
1322         node->add_property("mute-affects-main-outs", _mute_affects_main_outs?"yes":"no"); 
1323
1324         if (_edit_group) {
1325                 node->add_property("edit-group", _edit_group->name());
1326         }
1327         if (_mix_group) {
1328                 node->add_property("mix-group", _mix_group->name());
1329         }
1330
1331         string order_string;
1332         OrderKeys::iterator x = order_keys.begin(); 
1333
1334         while (x != order_keys.end()) {
1335                 order_string += (*x).first;
1336                 order_string += '=';
1337                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1338                 order_string += buf;
1339                 
1340                 ++x;
1341
1342                 if (x == order_keys.end()) {
1343                         break;
1344                 }
1345
1346                 order_string += ':';
1347         }
1348         node->add_property ("order-keys", order_string);
1349
1350         node->add_child_nocopy (IO::state (full_state));
1351
1352         if (_control_outs) {
1353                 XMLNode* cnode = new XMLNode (X_("ControlOuts"));
1354                 cnode->add_child_nocopy (_control_outs->state (full_state));
1355                 node->add_child_nocopy (*cnode);
1356         }
1357
1358         if (_comment.length()) {
1359                 XMLNode *cmt = node->add_child ("Comment");
1360                 cmt->add_content (_comment);
1361         }
1362
1363         if (full_state) {
1364                 string path;
1365
1366                 path = _session.snap_name();
1367                 path += "-gain-";
1368                 path += legalize_for_path (_name);
1369                 path += ".automation";
1370
1371                 /* XXX we didn't ask for a state save, we asked for the current state.
1372                    FIX ME!
1373                 */
1374
1375                 if (save_automation (path)) {
1376                         error << _("Could not get state of route.  Problem with save_automation") << endmsg;
1377                 }
1378
1379                 aevents = node->add_child ("Automation");
1380                 aevents->add_property ("path", path);
1381         }       
1382
1383         for (i = _redirects.begin(); i != _redirects.end(); ++i) {
1384                 node->add_child_nocopy((*i)->state (full_state));
1385         }
1386
1387         if (_extra_xml){
1388                 node->add_child_copy (*_extra_xml);
1389         }
1390         
1391         return *node;
1392 }
1393
1394 void
1395 Route::set_deferred_state ()
1396 {
1397         XMLNodeList nlist;
1398         XMLNodeConstIterator niter;
1399
1400         if (!deferred_state) {
1401                 return;
1402         }
1403
1404         nlist = deferred_state->children();
1405
1406         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1407                 add_redirect_from_xml (**niter);
1408         }
1409
1410         delete deferred_state;
1411         deferred_state = 0;
1412 }
1413
1414 void
1415 Route::add_redirect_from_xml (const XMLNode& node)
1416 {
1417         const XMLProperty *prop;
1418
1419         if (node.name() == "Send") {
1420                 
1421
1422                 try {
1423                         boost::shared_ptr<Send> send (new Send (_session, node));
1424                         add_redirect (send, this);
1425                 } 
1426                 
1427                 catch (failed_constructor &err) {
1428                         error << _("Send construction failed") << endmsg;
1429                         return;
1430                 }
1431                 
1432         } else if (node.name() == "Insert") {
1433                 
1434                 try {
1435                         if ((prop = node.property ("type")) != 0) {
1436
1437                                 boost::shared_ptr<Insert> insert;
1438
1439                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || prop->value() == "vst") {
1440
1441                                         insert.reset (new PluginInsert(_session, node));
1442                                         
1443                                 } else if (prop->value() == "port") {
1444
1445
1446                                         insert.reset (new PortInsert (_session, node));
1447
1448                                 } else {
1449
1450                                         error << string_compose(_("unknown Insert type \"%1\"; ignored"), prop->value()) << endmsg;
1451                                 }
1452
1453                                 add_redirect (insert, this);
1454                                 
1455                         } else {
1456                                 error << _("Insert XML node has no type property") << endmsg;
1457                         }
1458                 }
1459                 
1460                 catch (failed_constructor &err) {
1461                         warning << _("insert could not be created. Ignored.") << endmsg;
1462                         return;
1463                 }
1464         }
1465 }
1466
1467 int
1468 Route::set_state (const XMLNode& node)
1469 {
1470         XMLNodeList nlist;
1471         XMLNodeConstIterator niter;
1472         XMLNode *child;
1473         XMLPropertyList plist;
1474         const XMLProperty *prop;
1475
1476         if (node.name() != "Route"){
1477                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1478                 return -1;
1479         }
1480
1481         if ((prop = node.property ("flags")) != 0) {
1482                 int x;
1483                 sscanf (prop->value().c_str(), "0x%x", &x);
1484                 _flags = Flag (x);
1485         } else {
1486                 _flags = Flag (0);
1487         }
1488         
1489         if ((prop = node.property ("default-type")) != 0) {
1490                 _default_type = DataType(prop->value());
1491                 assert(_default_type != DataType::NIL);
1492         }
1493
1494         if ((prop = node.property ("phase-invert")) != 0) {
1495                 set_phase_invert(prop->value()=="yes"?true:false, this);
1496         }
1497
1498         if ((prop = node.property ("active")) != 0) {
1499                 set_active (prop->value() == "yes");
1500         }
1501
1502         if ((prop = node.property ("muted")) != 0) {
1503                 bool yn = prop->value()=="yes"?true:false; 
1504
1505                 /* force reset of mute status */
1506
1507                 _muted = !yn;
1508                 set_mute(yn, this);
1509                 mute_gain = desired_mute_gain;
1510         }
1511
1512         if ((prop = node.property ("soloed")) != 0) {
1513                 bool yn = prop->value()=="yes"?true:false; 
1514
1515                 /* force reset of solo status */
1516
1517                 _soloed = !yn;
1518                 set_solo (yn, this);
1519                 solo_gain = desired_solo_gain;
1520         }
1521
1522         if ((prop = node.property ("mute-affects-pre-fader")) != 0) {
1523                 _mute_affects_pre_fader = (prop->value()=="yes")?true:false;
1524         }
1525
1526         if ((prop = node.property ("mute-affects-post-fader")) != 0) {
1527                 _mute_affects_post_fader = (prop->value()=="yes")?true:false;
1528         }
1529
1530         if ((prop = node.property ("mute-affects-control-outs")) != 0) {
1531                 _mute_affects_control_outs = (prop->value()=="yes")?true:false;
1532         }
1533
1534         if ((prop = node.property ("mute-affects-main-outs")) != 0) {
1535                 _mute_affects_main_outs = (prop->value()=="yes")?true:false;
1536         }
1537
1538         if ((prop = node.property ("edit-group")) != 0) {
1539                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
1540                 if(edit_group == 0) {
1541                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1542                 } else {
1543                         set_edit_group(edit_group, this);
1544                 }
1545         }
1546
1547         if ((prop = node.property ("order-keys")) != 0) {
1548
1549                 long n;
1550
1551                 string::size_type colon, equal;
1552                 string remaining = prop->value();
1553
1554                 while (remaining.length()) {
1555
1556                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1557                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1558                                       << endmsg;
1559                         } else {
1560                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1561                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1562                                               << endmsg;
1563                                 } else {
1564                                         set_order_key (remaining.substr (0, equal), n);
1565                                 }
1566                         }
1567
1568                         colon = remaining.find_first_of (':');
1569
1570                         if (colon != string::npos) {
1571                                 remaining = remaining.substr (colon+1);
1572                         } else {
1573                                 break;
1574                         }
1575                 }
1576         }
1577
1578         nlist = node.children();
1579
1580         if (deferred_state) {
1581                 delete deferred_state;
1582         }
1583
1584         deferred_state = new XMLNode("deferred state");
1585
1586         /* set parent class properties before anything else */
1587
1588         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1589
1590                 child = *niter;
1591
1592                 if (child->name() == IO::state_node_name) {
1593
1594                         IO::set_state (*child);
1595                         break;
1596                 }
1597         }
1598                         
1599         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1600
1601                 child = *niter;
1602                         
1603                 if (child->name() == "Send") {
1604
1605
1606                         if (!IO::ports_legal) {
1607
1608                                 deferred_state->add_child_copy (*child);
1609
1610                         } else {
1611                                 add_redirect_from_xml (*child);
1612                         }
1613
1614                 } else if (child->name() == "Insert") {
1615                         
1616                         if (!IO::ports_legal) {
1617                                 
1618                                 deferred_state->add_child_copy (*child);
1619
1620                         } else {
1621                                 
1622                                 add_redirect_from_xml (*child);
1623                         }
1624
1625                 } else if (child->name() == "Automation") {
1626
1627                         XMLPropertyList plist;
1628                         XMLPropertyConstIterator piter;
1629                         XMLProperty *prop;
1630                         
1631                         plist = child->properties();
1632                         for (piter = plist.begin(); piter != plist.end(); ++piter) {
1633                                 prop = *piter;
1634                                 if (prop->name() == "path") {
1635                                         load_automation (prop->value());
1636                                 }
1637                         }
1638
1639                 } else if (child->name() == "ControlOuts") {
1640                         
1641                         string coutname = _name;
1642                         coutname += _("[control]");
1643
1644                         _control_outs = new IO (_session, coutname);
1645                         _control_outs->set_state (**(child->children().begin()));
1646
1647                 } else if (child->name() == "Comment") {
1648
1649                         /* XXX this is a terrible API design in libxml++ */
1650
1651                         XMLNode *cmt = *(child->children().begin());
1652                         _comment = cmt->content();
1653
1654                 } else if (child->name() == "extra") {
1655                         _extra_xml = new XMLNode (*child);
1656                 }
1657         }
1658
1659         if ((prop = node.property ("mix-group")) != 0) {
1660                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
1661                 if (mix_group == 0) {
1662                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1663                 }  else {
1664                         set_mix_group(mix_group, this);
1665                 }
1666         }
1667
1668         return 0;
1669 }
1670
1671 void
1672 Route::curve_reallocate ()
1673 {
1674 //      _gain_automation_curve.finish_resize ();
1675 //      _pan_automation_curve.finish_resize ();
1676 }
1677
1678 void
1679 Route::silence (jack_nframes_t nframes, jack_nframes_t offset)
1680 {
1681         if (!_silent) {
1682
1683                 IO::silence (nframes, offset);
1684
1685                 if (_control_outs) {
1686                         _control_outs->silence (nframes, offset);
1687                 }
1688
1689                 { 
1690                         Glib::RWLock::ReaderLock lm (redirect_lock, Glib::TRY_LOCK);
1691                         
1692                         if (lm.locked()) {
1693                                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1694                                         boost::shared_ptr<PluginInsert> pi;
1695                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
1696                                                 // skip plugins, they don't need anything when we're not active
1697                                                 continue;
1698                                         }
1699
1700                                         (*i)->silence (nframes, offset);
1701                                 }
1702
1703                                 if (nframes == _session.get_block_size() && offset == 0) {
1704                                         // _silent = true;
1705                                 }
1706                         }
1707                 }
1708                 
1709         }
1710 }       
1711
1712 int
1713 Route::set_control_outs (const vector<string>& ports)
1714 {
1715         Glib::Mutex::Lock lm (control_outs_lock);
1716         vector<string>::const_iterator i;
1717
1718         if (_control_outs) {
1719                 delete _control_outs;
1720                 _control_outs = 0;
1721         }
1722         
1723         if (ports.empty()) {
1724                 return 0;
1725         }
1726  
1727         string coutname = _name;
1728         coutname += _("[control]");
1729         
1730         _control_outs = new IO (_session, coutname);
1731
1732         /* our control outs need as many outputs as we
1733            have audio outputs. we track the changes in ::output_change_handler().
1734         */
1735
1736         _control_outs->ensure_io (ChanCount::ZERO, ChanCount(DataType::AUDIO, n_outputs().get(DataType::AUDIO)), true, this);
1737  
1738         return 0;
1739 }       
1740
1741 void
1742 Route::set_edit_group (RouteGroup *eg, void *src)
1743
1744 {
1745         if (eg == _edit_group) {
1746                 return;
1747         }
1748
1749         if (_edit_group) {
1750                 _edit_group->remove (this);
1751         }
1752
1753         if ((_edit_group = eg) != 0) {
1754                 _edit_group->add (this);
1755         }
1756
1757         _session.set_dirty ();
1758         edit_group_changed (src); /* EMIT SIGNAL */
1759 }
1760
1761 void
1762 Route::drop_edit_group (void *src)
1763 {
1764         _edit_group = 0;
1765         _session.set_dirty ();
1766         edit_group_changed (src); /* EMIT SIGNAL */
1767 }
1768
1769 void
1770 Route::set_mix_group (RouteGroup *mg, void *src)
1771
1772 {
1773         if (mg == _mix_group) {
1774                 return;
1775         }
1776
1777         if (_mix_group) {
1778                 _mix_group->remove (this);
1779         }
1780
1781         if ((_mix_group = mg) != 0) {
1782                 _mix_group->add (this);
1783         }
1784
1785         _session.set_dirty ();
1786         mix_group_changed (src); /* EMIT SIGNAL */
1787 }
1788
1789 void
1790 Route::drop_mix_group (void *src)
1791 {
1792         _mix_group = 0;
1793         _session.set_dirty ();
1794         mix_group_changed (src); /* EMIT SIGNAL */
1795 }
1796
1797 void
1798 Route::set_comment (string cmt, void *src)
1799 {
1800         _comment = cmt;
1801         comment_changed (src);
1802         _session.set_dirty ();
1803 }
1804
1805 bool
1806 Route::feeds (boost::shared_ptr<Route> other)
1807 {
1808         uint32_t i, j;
1809
1810         IO& self = *this;
1811         uint32_t no = self.n_outputs().get_total();
1812         uint32_t ni = other->n_inputs ().get_total();
1813
1814         for (i = 0; i < no; ++i) {
1815                 for (j = 0; j < ni; ++j) {
1816                         if (self.output(i)->connected_to (other->input(j)->name())) {
1817                                 return true;
1818                         }
1819                 }
1820         }
1821
1822         /* check Redirects which may also interconnect Routes */
1823
1824         for (RedirectList::iterator r = _redirects.begin(); r != _redirects.end(); r++) {
1825
1826                 no = (*r)->n_outputs().get_total();
1827
1828                 for (i = 0; i < no; ++i) {
1829                         for (j = 0; j < ni; ++j) {
1830                                 if ((*r)->output(i)->connected_to (other->input (j)->name())) {
1831                                         return true;
1832                                 }
1833                         }
1834                 }
1835         }
1836
1837         /* check for control room outputs which may also interconnect Routes */
1838
1839         if (_control_outs) {
1840
1841                 no = _control_outs->n_outputs().get_total();
1842                 
1843                 for (i = 0; i < no; ++i) {
1844                         for (j = 0; j < ni; ++j) {
1845                                 if (_control_outs->output(i)->connected_to (other->input (j)->name())) {
1846                                         return true;
1847                                 }
1848                         }
1849                 }
1850         }
1851
1852         return false;
1853 }
1854
1855 void
1856 Route::set_mute_config (mute_type t, bool onoff, void *src)
1857 {
1858         switch (t) {
1859         case PRE_FADER:
1860                 _mute_affects_pre_fader = onoff;
1861                  pre_fader_changed(src); /* EMIT SIGNAL */
1862                 break;
1863
1864         case POST_FADER:
1865                 _mute_affects_post_fader = onoff;
1866                  post_fader_changed(src); /* EMIT SIGNAL */
1867                 break;
1868
1869         case CONTROL_OUTS:
1870                 _mute_affects_control_outs = onoff;
1871                  control_outs_changed(src); /* EMIT SIGNAL */
1872                 break;
1873
1874         case MAIN_OUTS:
1875                 _mute_affects_main_outs = onoff;
1876                  main_outs_changed(src); /* EMIT SIGNAL */
1877                 break;
1878         }
1879 }
1880
1881 bool
1882 Route::get_mute_config (mute_type t)
1883 {
1884         bool onoff = false;
1885         
1886         switch (t){
1887         case PRE_FADER:
1888                 onoff = _mute_affects_pre_fader; 
1889                 break;
1890         case POST_FADER:
1891                 onoff = _mute_affects_post_fader;
1892                 break;
1893         case CONTROL_OUTS:
1894                 onoff = _mute_affects_control_outs;
1895                 break;
1896         case MAIN_OUTS:
1897                 onoff = _mute_affects_main_outs;
1898                 break;
1899         }
1900         
1901         return onoff;
1902 }
1903
1904 void
1905 Route::set_active (bool yn)
1906 {
1907         _active = yn; 
1908          active_changed(); /* EMIT SIGNAL */
1909 }
1910
1911 void
1912 Route::handle_transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_redirects)
1913 {
1914         jack_nframes_t now = _session.transport_frame();
1915
1916         {
1917                 Glib::RWLock::ReaderLock lm (redirect_lock);
1918
1919                 if (!did_locate) {
1920                         automation_snapshot (now);
1921                 }
1922
1923                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1924                         
1925                         if (Config->get_plugins_stop_with_transport() && can_flush_redirects) {
1926                                 (*i)->deactivate ();
1927                                 (*i)->activate ();
1928                         }
1929                         
1930                         (*i)->transport_stopped (now);
1931                 }
1932         }
1933
1934         IO::transport_stopped (now);
1935  
1936         _roll_delay = _initial_delay;
1937 }
1938
1939 UndoAction
1940 Route::get_memento() const
1941 {
1942         void (Route::*pmf)(state_id_t) = &Route::set_state;
1943         return sigc::bind (mem_fun (*(const_cast<Route *>(this)), pmf), _current_state_id);
1944 }
1945
1946 void
1947 Route::set_state (state_id_t id)
1948 {
1949         return;
1950 }
1951
1952 void
1953 Route::input_change_handler (IOChange change, void *ignored)
1954 {
1955         if (change & ConfigurationChanged) {
1956                 reset_plugin_counts (0);
1957         }
1958 }
1959
1960 void
1961 Route::output_change_handler (IOChange change, void *ignored)
1962 {
1963         if (change & ConfigurationChanged) {
1964                 if (_control_outs) {
1965                         _control_outs->ensure_io (ChanCount::ZERO, ChanCount(DataType::AUDIO, n_outputs().get(DataType::AUDIO)), true, this);
1966                 }
1967                 
1968                 reset_plugin_counts (0);
1969         }
1970 }
1971
1972 uint32_t
1973 Route::pans_required () const
1974 {
1975         if (n_outputs().get(DataType::AUDIO) < 2) {
1976                 return 0;
1977         }
1978         
1979         return max (n_inputs ().get(DataType::AUDIO), static_cast<size_t>(redirect_max_outs.get(DataType::AUDIO)));
1980 }
1981
1982 int 
1983 Route::no_roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, 
1984                    bool session_state_changing, bool can_record, bool rec_monitors_input)
1985 {
1986         if (n_outputs().get_total() == 0) {
1987                 return 0;
1988         }
1989
1990         if (session_state_changing || !_active)  {
1991                 silence (nframes, offset);
1992                 return 0;
1993         }
1994
1995         apply_gain_automation = false;
1996         
1997         if (n_inputs().get_total()) {
1998                 passthru (start_frame, end_frame, nframes, offset, 0, false);
1999         } else {
2000                 silence (nframes, offset);
2001         }
2002
2003         return 0;
2004 }
2005
2006 jack_nframes_t
2007 Route::check_initial_delay (jack_nframes_t nframes, jack_nframes_t& offset, jack_nframes_t& transport_frame)
2008 {
2009         if (_roll_delay > nframes) {
2010
2011                 _roll_delay -= nframes;
2012                 silence (nframes, offset);
2013                 /* transport frame is not legal for caller to use */
2014                 return 0;
2015
2016         } else if (_roll_delay > 0) {
2017
2018                 nframes -= _roll_delay;
2019
2020                 silence (_roll_delay, offset);
2021
2022                 offset += _roll_delay;
2023                 transport_frame += _roll_delay;
2024
2025                 _roll_delay = 0;
2026         }
2027
2028         return nframes;
2029 }
2030
2031 int
2032 Route::roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, int declick,
2033              bool can_record, bool rec_monitors_input)
2034 {
2035         {
2036                 Glib::RWLock::ReaderLock lm (redirect_lock, Glib::TRY_LOCK);
2037                 if (lm.locked()) {
2038                         // automation snapshot can also be called from the non-rt context
2039                         // and it uses the redirect list, so we take the lock out here
2040                         automation_snapshot (_session.transport_frame());
2041                 }
2042         }
2043                 
2044         if ((n_outputs().get_total() == 0 && _redirects.empty()) || n_inputs().get_total() == 0 || !_active) {
2045                 silence (nframes, offset);
2046                 return 0;
2047         }
2048         
2049         jack_nframes_t unused = 0;
2050
2051         if ((nframes = check_initial_delay (nframes, offset, unused)) == 0) {
2052                 return 0;
2053         }
2054
2055         _silent = false;
2056
2057         apply_gain_automation = false;
2058
2059         { 
2060                 Glib::Mutex::Lock am (automation_lock, Glib::TRY_LOCK);
2061                 
2062                 if (am.locked() && _session.transport_rolling()) {
2063                         
2064                         if (gain_automation_playback()) {
2065                                 apply_gain_automation = _gain_automation_curve.rt_safe_get_vector (start_frame, end_frame, _session.gain_automation_buffer(), nframes);
2066                         }
2067                 }
2068         }
2069
2070         passthru (start_frame, end_frame, nframes, offset, declick, false);
2071
2072         return 0;
2073 }
2074
2075 int
2076 Route::silent_roll (jack_nframes_t nframes, jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t offset, 
2077                     bool can_record, bool rec_monitors_input)
2078 {
2079         silence (nframes, offset);
2080         return 0;
2081 }
2082
2083 void
2084 Route::toggle_monitor_input ()
2085 {
2086         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2087                 i->request_monitor_input( ! i->monitoring_input());
2088         }
2089 }
2090
2091 bool
2092 Route::has_external_redirects () const
2093 {
2094         boost::shared_ptr<const PortInsert> pi;
2095         
2096         for (RedirectList::const_iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2097                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2098
2099                         for (PortSet::const_iterator port = pi->outputs().begin();
2100                                         port != pi->outputs().end(); ++port) {
2101                                 
2102                                 string port_name = port->name();
2103                                 string client_name = port_name.substr (0, port_name.find(':'));
2104
2105                                 /* only say "yes" if the redirect is actually in use */
2106                                 
2107                                 if (client_name != "ardour" && pi->active()) {
2108                                         return true;
2109                                 }
2110                         }
2111                 }
2112         }
2113
2114         return false;
2115 }
2116
2117 void
2118 Route::flush_redirects ()
2119 {
2120         /* XXX shouldn't really try to take this lock, since
2121            this is called from the RT audio thread.
2122         */
2123
2124         Glib::RWLock::ReaderLock lm (redirect_lock);
2125
2126         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2127                 (*i)->deactivate ();
2128                 (*i)->activate ();
2129         }
2130 }
2131
2132 void
2133 Route::set_meter_point (MeterPoint p, void *src)
2134 {
2135         if (_meter_point != p) {
2136                 _meter_point = p;
2137                  meter_change (src); /* EMIT SIGNAL */
2138                 _session.set_dirty ();
2139         }
2140 }
2141
2142 jack_nframes_t
2143 Route::update_total_latency ()
2144 {
2145         _own_latency = 0;
2146
2147         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2148                 if ((*i)->active ()) {
2149                         _own_latency += (*i)->latency ();
2150                 }
2151         }
2152
2153         set_port_latency (_own_latency);
2154
2155         /* this (virtual) function is used for pure Routes,
2156            not derived classes like AudioTrack.  this means
2157            that the data processed here comes from an input
2158            port, not prerecorded material, and therefore we
2159            have to take into account any input latency.
2160         */
2161
2162         _own_latency += input_latency ();
2163
2164         return _own_latency;
2165 }
2166
2167 void
2168 Route::set_latency_delay (jack_nframes_t longest_session_latency)
2169 {
2170         _initial_delay = longest_session_latency - _own_latency;
2171
2172         if (_session.transport_stopped()) {
2173                 _roll_delay = _initial_delay;
2174         }
2175 }
2176
2177 void
2178 Route::automation_snapshot (jack_nframes_t now)
2179 {
2180         IO::automation_snapshot (now);
2181
2182         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2183                 (*i)->automation_snapshot (now);
2184         }
2185 }
2186
2187 Route::ToggleControllable::ToggleControllable (Route& s, ToggleType tp)
2188         : route (s), type(tp)
2189 {
2190         
2191 }
2192
2193 void
2194 Route::ToggleControllable::set_value (float val)
2195 {
2196         bool bval = ((val >= 0.5f) ? true: false);
2197         
2198         switch (type) {
2199         case MuteControl:
2200                 route.set_mute (bval, this);
2201                 break;
2202         case SoloControl:
2203                 route.set_solo (bval, this);
2204                 break;
2205         default:
2206                 break;
2207         }
2208 }
2209
2210 float
2211 Route::ToggleControllable::get_value (void) const
2212 {
2213         float val = 0.0f;
2214         
2215         switch (type) {
2216         case MuteControl:
2217                 val = route.muted() ? 1.0f : 0.0f;
2218                 break;
2219         case SoloControl:
2220                 val = route.soloed() ? 1.0f : 0.0f;
2221                 break;
2222         default:
2223                 break;
2224         }
2225
2226         return val;
2227 }
2228
2229 void 
2230 Route::set_block_size (jack_nframes_t nframes)
2231 {
2232         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2233                 (*i)->set_block_size (nframes);
2234         }
2235 }
2236
2237 void
2238 Route::redirect_active_proxy (Redirect* ignored, void* ignored_src)
2239 {
2240         _session.update_latency_compensation (false, false);
2241 }
2242
2243 void
2244 Route::protect_automation ()
2245 {
2246         switch (gain_automation_state()) {
2247         case Write:
2248         case Touch:
2249                 set_gain_automation_state (Off);
2250                 break;
2251         default:
2252                 break;
2253         }
2254
2255         switch (panner().automation_state ()) {
2256         case Write:
2257         case Touch:
2258                 panner().set_automation_state (Off);
2259                 break;
2260         default:
2261                 break;
2262         }
2263         
2264         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2265                 boost::shared_ptr<PluginInsert> pi;
2266                 if ((pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2267                         pi->protect_automation ();
2268                 }
2269         }
2270 }
2271
2272 void
2273 Route::set_pending_declick (int declick)
2274 {
2275         if (_declickable) {
2276                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2277                 if (declick) {
2278                         _pending_declick = declick;
2279                 }
2280                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2281         } else {
2282                 _pending_declick = 0;
2283         }
2284
2285 }