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